- 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
Matching MongoDB collection items by id?
To match collection items by id, use $in in MongoDB. Let us create a collection with documents −
> db.demo528.insertOne({"Name":"Chris",Age:21});{ "acknowledged" : true, "insertedId" : ObjectId("5e8b00d2ef4dcbee04fbbbe0") } > db.demo528.insertOne({"Name":"Bob",Age:22});{ "acknowledged" : true, "insertedId" : ObjectId("5e8b00d9ef4dcbee04fbbbe1") } > db.demo528.insertOne({"Name":"David",Age:20});{ "acknowledged" : true, "insertedId" : ObjectId("5e8b00e0ef4dcbee04fbbbe2") }
Display all documents from a collection with the help of find() method −
> db.demo528.find();
This will produce the following output −
{ "_id" : ObjectId("5e8b00d2ef4dcbee04fbbbe0"), "Name" : "Chris", "Age" : 21 } { "_id" : ObjectId("5e8b00d9ef4dcbee04fbbbe1"), "Name" : "Bob", "Age" : 22 } { "_id" : ObjectId("5e8b00e0ef4dcbee04fbbbe2"), "Name" : "David", "Age" : 20 }
Following is the query to match collection item by id −
> db.demo528.find({ _id: {$in:[ObjectId("5e8b00d2ef4dcbee04fbbbe0"),ObjectId("5e8b00e0ef4dcbee04fbbbe2")]} });
This will produce the following output −
{ "_id" : ObjectId("5e8b00d2ef4dcbee04fbbbe0"), "Name" : "Chris", "Age" : 21 } { "_id" : ObjectId("5e8b00e0ef4dcbee04fbbbe2"), "Name" : "David", "Age" : 20 }
Advertisements