Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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 -
$inoperator matches documents where_idis 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.
Advertisements
