Fetch records from a subdocument array wherein id begins from 234 in MongoDB

MongoDBDatabaseBig Data Analytics

To fetch records from a subdocument array, use $unwind along with $push. For ids beginning from 234, use regex in MongoDB.

Let us create a collection with documents −

> db.demo556.insertOne(
... {
...    _id:101,
...    details:[
...       {
...          id:"234336",
...          Name:"Chris"
...       },
...       {
...          id:"123456",
...          Name:"Bob"
...       },
...       {
...          id:"234987",
...          Name:"Carol"
...       },
...       {
...          id:"989768",
...          Name:"David"
...       },
...       {
...          id:"234888",
...          Name:"Sam"
...       },
...       {
...          id:"847656",
...          Name:"John"
...       }
...    ]
... }
... );
{ "acknowledged" : true, "insertedId" : 101 }

Display all documents from a collection with the help of find() method −

> db.demo556.find();

This will produce the following output −

{ "_id" : 101, "details" : [
   { "id" : "234336", "Name" : "Chris" },
   { "id" : "123456", "Name" : "Bob" },
   { "id" : "234987", "Name" : "Carol" },
   { "id" : "989768", "Name" : "David" },
   { "id" : "234888", "Name" : "Sam" },
   { "id" : "847656", "Name" : "John" } 
] }

Following is the query to fetch records from a subdocument array −

> db.demo556.aggregate({
...    $match: {
...       "_id": 101
...    }
... }, {
...    $unwind: "$details"
... }, {
...    $match: {
...       "details.id": {
...          $regex: /^234/
...       }
...    }
... }, {
...    $group: {
...       _id: "$_id",
...       "Detail": {
...          $push: "$details"
...       }
...    }
... }).pretty();

This will produce the following output −

{
   "_id" : 101,
   "Detail" : [
      {
         "id" : "234336",
         "Name" : "Chris"
      },
      {
         "id" : "234987",
         "Name" : "Carol"
      },
      {
         "id" : "234888",
         "Name" : "Sam"
      }
   ]
}
raja
Updated on 14-May-2020 08:07:30

Advertisements