Query to retrieve multiple items in an array in MongoDB?

MongoDBDatabaseBig Data Analytics

To retrieve multiple items in an array, use aggregate framework. Let us first create a collection with documents −

> db.retrieveMultipleDemo.insertOne(
...   {
...      "UserDetails":
...      [
...         { "_id": "101", "UserName":"John", "UserAge": 23 },
...         { "_id": "102", "UserName":"Carol", "UserAge": 21 },
...         { "_id": "103", "UserName":"David", "UserAge": 23},
...         { "_id": "104", "UserName":"Sam", "UserAge": 25}
...      ]
...   }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd40c85edc6604c74817cf0")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.retrieveMultipleDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cd40c85edc6604c74817cf0"),
   "UserDetails" : [
      {
         "_id" : "101",
         "UserName" : "John",
         "UserAge" : 23
      },
      {
         "_id" : "102",
         "UserName" : "Carol",
         "UserAge" : 21
      },
      {
         "_id" : "103",
         "UserName" : "David",
         "UserAge" : 23
      },
      {
         "_id" : "104",
         "UserName" : "Sam",
         "UserAge" : 25
      }
   ]
}

Following is the query to retrieve multiple items in an array −

> db.retrieveMultipleDemo.aggregate([
...   {$unwind:"$UserDetails"},
...   {$match:{"UserDetails._id":{$in:myIds},"UserDetails.UserAge":23}},
...   {$group:{"_id":"_id","UserDetails":{$push:"$UserDetails"}}},
...   {$project:{"_id":0,"UserDetails":1}}
... ]);

This will produce the following output −

{ "UserDetails" : [ { "_id" : "101", "UserName" : "John", "UserAge" : 23 }, { "_id" : "103", "UserName" : "David", "UserAge" : 23 } ] }
raja
Published on 23-May-2019 08:38:31
Advertisements