Matching MongoDB collection items by id?

To match collection items by id, use the $in operator in MongoDB. This allows you to query multiple documents by their specific ObjectId values in a single operation.

Syntax

db.collection.find({
    _id: { $in: [ObjectId("id1"), ObjectId("id2"), ObjectId("id3")] }
});

Create Sample Data

db.demo528.insertMany([
    {"Name": "Chris", "Age": 21},
    {"Name": "Bob", "Age": 22},
    {"Name": "David", "Age": 20}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e8b00d2ef4dcbee04fbbbe0"),
        ObjectId("5e8b00d9ef4dcbee04fbbbe1"),
        ObjectId("5e8b00e0ef4dcbee04fbbbe2")
    ]
}

Display All Documents

db.demo528.find();
{ "_id": ObjectId("5e8b00d2ef4dcbee04fbbbe0"), "Name": "Chris", "Age": 21 }
{ "_id": ObjectId("5e8b00d9ef4dcbee04fbbbe1"), "Name": "Bob", "Age": 22 }
{ "_id": ObjectId("5e8b00e0ef4dcbee04fbbbe2"), "Name": "David", "Age": 20 }

Example: Match Multiple Documents by ID

Query to match documents with specific ObjectId values ?

db.demo528.find({
    _id: {
        $in: [
            ObjectId("5e8b00d2ef4dcbee04fbbbe0"),
            ObjectId("5e8b00e0ef4dcbee04fbbbe2")
        ]
    }
});
{ "_id": ObjectId("5e8b00d2ef4dcbee04fbbbe0"), "Name": "Chris", "Age": 21 }
{ "_id": ObjectId("5e8b00e0ef4dcbee04fbbbe2"), "Name": "David", "Age": 20 }

Key Points

  • The $in operator matches any document where the field value equals any value in the specified array.
  • Use ObjectId() constructor when querying by _id field to ensure proper data type matching.

Conclusion

The $in operator with ObjectId values provides an efficient way to retrieve multiple documents by their unique identifiers in a single query operation.

Updated on: 2026-03-15T03:23:56+05:30

468 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements