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
Perform $lookup to array of object id's in MongoDB?
To perform $lookup on an array of ObjectIds in MongoDB, use the $lookup aggregation stage with a pipeline approach. This performs a left outer join between collections where one collection contains an array of ObjectIds referencing documents in another collection.
Syntax
db.collection.aggregate([
{
$lookup: {
from: "targetCollection",
let: { arrayField: "$arrayOfObjectIds" },
pipeline: [
{ $match: { $expr: { $in: ["$_id", "$$arrayField"] } } }
],
as: "joinedData"
}
}
])
Create Sample Data
First, create a collection with user documents ?
db.users.insertMany([
{ Name: "Chris" },
{ Name: "David" }
]);
{
"acknowledged": true,
"insertedIds": {
"0": ObjectId("5e5e782317aa3ef9ab8ab207"),
"1": ObjectId("5e5e782317aa3ef9ab8ab208")
}
}
Next, create a collection containing an array of ObjectIds referencing the users ?
db.groups.insertOne({
"details": [
ObjectId("5e5e782317aa3ef9ab8ab207"),
ObjectId("5e5e782317aa3ef9ab8ab208")
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e5e787817aa3ef9ab8ab209")
}
Perform $lookup with Array of ObjectIds
db.groups.aggregate([
{
$lookup: {
from: "users",
let: { details: "$details" },
pipeline: [
{ $match: { $expr: { $in: ["$_id", "$$details"] } } }
],
as: "matchedUsers"
}
}
]);
{
"_id": ObjectId("5e5e787817aa3ef9ab8ab209"),
"details": [
ObjectId("5e5e782317aa3ef9ab8ab207"),
ObjectId("5e5e782317aa3ef9ab8ab208")
],
"matchedUsers": [
{ "_id": ObjectId("5e5e782317aa3ef9ab8ab207"), "Name": "Chris" },
{ "_id": ObjectId("5e5e782317aa3ef9ab8ab208"), "Name": "David" }
]
}
How It Works
-
$let defines a variable
detailscontaining the array of ObjectIds -
$match with $expr checks if each document's
_idexists in the array using$in -
$$details references the variable defined in the
letstage - The as field specifies the output array name for joined documents
Conclusion
Use $lookup with a pipeline approach to join collections when one contains an array of ObjectIds. The $in operator within $expr efficiently matches documents whose _id exists in the reference array.
Advertisements
