- 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
MongoDB query to match documents whose _id is in an array as part of a subdocument?
Let us create a collection with documents −
> db.demo568.insertOne({ _id: 101, details: [ {id : 101 }, { id:103 } ] }); { "acknowledged" : true, "insertedId" : 101 }
Display all documents from a collection with the help of find() method −
> db.demo568.find();
This will produce the following output −
{ "_id" : 101, "details" : [ { "id" : 101 }, { "id" : 103 } ] } Following is the query to create second collection: > db.demo569.insertOne({ _id: 101, details: "John" }) { "acknowledged" : true, "insertedId" : 101 } > db.demo569.insertOne({ _id: 102, details: "Chris" }) { "acknowledged" : true, "insertedId" : 102 } > db.demo569.insertOne({ _id: 103, details: "David" }) { "acknowledged" : true, "insertedId" : 103 }
Display all documents from a collection with the help of find() method −
> db.demo569.find();
This will produce the following output −
{ "_id" : 101, "details" : "John" } { "_id" : 102, "details" : "Chris" } { "_id" : 103, "details" : "David" }
Following is the query to match documents whose _id is in an array as part of a subdocument −
> db.demo569.find({ '_id': { '$in': db.demo568.distinct('details.id', {'_id': 101}) }})
This will produce the following output −
{ "_id" : 101, "details" : "John" } { "_id" : 103, "details" : "David" }
Advertisements