To do this, just use dot notation and find() in MongoDB. Let us create a collection containing 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 the documents in the 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 } } ] }
The following is Query to get all documents in an array that contain another document -
> 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 } } ] }
The above is the detailed content of How to get all documents in an array that contain another document using MongoDB?. For more information, please follow other related articles on the PHP Chinese website!