- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 } } ] }
Advertisements