Fetch specific multiple documents in MongoDB

To fetch specific multiple documents in MongoDB, use the $in operator to match documents where a field value equals any value in a specified array.

Syntax

db.collection.find({
    "field": { $in: [value1, value2, value3, ...] }
});

Sample Data

Let us create a collection with documents −

db.demo593.insertMany([
    { id: 1, "Name": "Chris" },
    { id: 2, "Name": "John" },
    { id: 3, "Name": "Bob" },
    { id: 4, "Name": "Sam" }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e93177dfd2d90c177b5bcd9"),
        ObjectId("5e931785fd2d90c177b5bcda"),
        ObjectId("5e93178cfd2d90c177b5bcdb"),
        ObjectId("5e931792fd2d90c177b5bcdc")
    ]
}

Display All Documents

db.demo593.find();
{ "_id": ObjectId("5e93177dfd2d90c177b5bcd9"), "id": 1, "Name": "Chris" }
{ "_id": ObjectId("5e931785fd2d90c177b5bcda"), "id": 2, "Name": "John" }
{ "_id": ObjectId("5e93178cfd2d90c177b5bcdb"), "id": 3, "Name": "Bob" }
{ "_id": ObjectId("5e931792fd2d90c177b5bcdc"), "id": 4, "Name": "Sam" }

Example: Fetch Multiple Specific Documents

Following is the query to fetch documents with id 1 and 3 −

db.demo593.find({ id: { $in: [1, 3] } });
{ "_id": ObjectId("5e93177dfd2d90c177b5bcd9"), "id": 1, "Name": "Chris" }
{ "_id": ObjectId("5e93178cfd2d90c177b5bcdb"), "id": 3, "Name": "Bob" }

Conclusion

The $in operator is ideal for fetching multiple documents based on specific field values. It accepts an array of values and returns documents where the field matches any value in that array.

Updated on: 2026-03-15T03:46:31+05:30

539 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements