How to get all docs which contain another doc in an array with MongoDB?

MongoDBDatabaseBig Data Analytics

For this, simply use dot notation with find() in MongoDB. Let us create a collection with documents −

> db.demo465.insertOne(
... {
...    id: 101,
...    details: [{
...       Name: "Chris",
...       Info: {
...          Subject: "MongoDB",
...          Marks:67
...       }
...    }, {
...          Name: "David",
...          Info: {
...             Subject: "MySQL",
...             Marks:78
...       }
...    }]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e80421bb0f3fa88e2279061")
}
>
> db.demo465.insertOne(
... {
...    id: 102,
...    details: [{
...       Name: "Bob",
...       Info: {
...          Subject: "Java",
...          Marks:45
...       }
...    }, {
...          Name: "Carol",
...          Info: {
...             Subject: "C",
...             Marks:67
...          }
...       }]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e80421cb0f3fa88e2279062")
}

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

> db.demo465.find();

This will produce the following output −

{ "_id" : ObjectId("5e80421bb0f3fa88e2279061"), "id" : 101, "details" : [ { "Name" : "Chris",
"Info" : { "Subject" : "MongoDB", "Marks" : 67 } }, { "Name" : "David", "Info" : { "Subject" :
"MySQL", "Marks" : 78 } } ] }
{ "_id" : ObjectId("5e80421cb0f3fa88e2279062"), "id" : 102, "details" : [ { "Name" : "Bob",
"Info" : { "Subject" : "Java", "Marks" : 45 } }, { "Name" : "Carol", "Info" : { "Subject" : "C",
"Marks" : 67 } } ] }

Following is the query to get all docs which contain another doc in an array −

> db.demo465.find({"details.Name":"Bob"});

This will produce the following output −

{ "_id" : ObjectId("5e80421cb0f3fa88e2279062"), "id" : 102, "details" : [ { "Name" : "Bob",
"Info" : { "Subject" : "Java", "Marks" : 45 } }, { "Name" : "Carol", "Info" : { "Subject" : "C",
"Marks" : 67 } } ] }
raja
Published on 11-May-2020 13:02:57
Advertisements