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

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



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 } } ] }
Updated on: 2020-05-11T09:33:14+05:30

105 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements