- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 }
- Related Articles
- Sort id and reverse the items with MongoDB
- MongoDB Aggregate JSON array field for the matching field of other collection?
- Sort MongoDB Collection by Array value?
- How to find by id in MongoDB?
- MongoDB find by multiple array items?
- Group by dates in a MongoDB collection?
- Filtering MongoDB items by fields and subfields?
- MongoDB exact array matching
- Can I retrieve multiple documents from MongoDB by id?
- MongoDB find by multiple array items using $in?
- Searching for an array entry via its id in a MongoDB collection and performing update
- Retrieving specific documents from collection by _id in MongoDB
- Program to count items matching a rule using Python
- Hide id field in MongoDB
- Finding matching records with LIKE in MongoDB?

Advertisements