MongoDB query to match documents whose _id is in an array as part of a subdocument?

To match documents whose _id is in an array stored as part of a subdocument, use the $in operator combined with distinct() to extract array values from the subdocument field.

Syntax

db.targetCollection.find({
    "_id": { "$in": db.sourceCollection.distinct("arrayField.subField", {filter}) }
});

Sample Data

Create a collection with an array of subdocuments containing IDs ?

db.demo568.insertOne({ 
    _id: 101, 
    details: [ 
        { id: 101 }, 
        { id: 103 } 
    ] 
});
{ "acknowledged": true, "insertedId": 101 }

Create a second collection with documents to match against ?

db.demo569.insertMany([
    { _id: 101, details: "John" },
    { _id: 102, details: "Chris" },
    { _id: 103, details: "David" }
]);
{ "acknowledged": true, "insertedIds": { "0": 101, "1": 102, "2": 103 } }

Example: Match Documents Using Array IDs

Find documents in demo569 whose _id matches any ID in the details array of document 101 from demo568 ?

db.demo569.find({ 
    "_id": { 
        "$in": db.demo568.distinct("details.id", {"_id": 101}) 
    }
});
{ "_id": 101, "details": "John" }
{ "_id": 103, "details": "David" }

How It Works

  • db.demo568.distinct("details.id", {"_id": 101}) extracts [101, 103] from the array
  • $in operator matches documents where _id is 101 or 103
  • Returns matching documents from the target collection

Conclusion

Use $in with distinct() to match documents whose _id exists in an array stored within subdocuments. This approach efficiently queries across collections using extracted array values as matching criteria.

Updated on: 2026-03-15T03:36:29+05:30

225 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements