Querying from part of object in an array with MongoDB


To query from part of object in an array, use $findOne() and $all. Let us first create a collection with documents −

> db.demo25.insertOne(
... {
...
...    "Details":[
...       {
...          "UserId":"Carol101",
...          "UserName":"Carol"
...       },
...       {
...          "UserId":"David102",
...          "UserName":"David"
...       }
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e14c86e22d07d3b95082e77")
}
> db.demo25.insertOne(
... {
...
...    "Details":[
...       {
...          "UserId":"Chris101",
...          "UserName":"Chris"
...       },
...       {
...          "UserId":"Mike102",
...          "UserName":"Mike"
...       }
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e14c86f22d07d3b95082e78")
}

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

> db.demo25.find();

This will produce the following output −

{ "_id" : ObjectId("5e14c86e22d07d3b95082e77"), "Details" : [ { "UserId" : "Carol101", "UserName" : "Carol" }, { "UserId" : "David102", "UserName" : "David" } ] }
{ "_id" : ObjectId("5e14c86f22d07d3b95082e78"), "Details" : [ { "UserId" : "Chris101", "UserName" : "Chris" }, { "UserId" : "Mike102", "UserName" : "Mike" } ] }

Here is how to query from part of object in array −

> db.demo25.findOne({ "Details.UserId":{$all : ["Carol101","David102"]}});

This will produce the following output −

{
   "_id" : ObjectId("5e14c86e22d07d3b95082e77"),
   "Details" : [
      {
         "UserId" : "Carol101",
         "UserName" : "Carol"
      },
      {
         "UserId" : "David102",
         "UserName" : "David"
      }
   ]
}

Updated on: 02-Apr-2020

101 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements