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 Aggregate JSON array field for the matching field of other collection?
To aggregate JSON array field for matching fields from another collection in MongoDB, use $lookup combined with $unwind to join collections based on array elements, then reconstruct the result using $group.
Syntax
db.collection1.aggregate([
{ $unwind: "$arrayField" },
{ $lookup: {
from: "collection2",
localField: "arrayField.joinField",
foreignField: "_id",
as: "matchedData"
}},
{ $project: {
"_id": 1,
"arrayField.newField": { $arrayElemAt: ["$matchedData.targetField", 0] }
}},
{ $group: {
_id: "$_id",
arrayField: { $push: "$arrayField" }
}}
]);
Sample Data
Create the first collection with an array field ?
db.demo101.insertOne({
"_id": "1",
"Details": [
{ "PId": "200" },
{ "PId": "201" },
{ "PId": "201" }
]
});
{ "acknowledged": true, "insertedId": "1" }
Create the second collection with matching reference data ?
db.demo102.insertMany([
{ "_id": "200", "CustEmailId": "John@gmail.com" },
{ "_id": "201", "CustEmailId": "Carol@gmail.com" }
]);
{ "acknowledged": true, "insertedIds": ["200", "201"] }
Example
Aggregate to replace PId values with corresponding email addresses ?
db.demo101.aggregate([
{ $unwind: "$Details" },
{ $lookup: {
from: "demo102",
localField: "Details.PId",
foreignField: "_id",
as: "out"
}},
{ $project: {
"_id": 1,
"Details.PId": { $arrayElemAt: ["$out.CustEmailId", 0] }
}},
{ $group: {
_id: "$_id",
Details: { $push: "$Details" }
}}
]);
{
"_id": "1",
"Details": [
{ "PId": "John@gmail.com" },
{ "PId": "Carol@gmail.com" },
{ "PId": "Carol@gmail.com" }
]
}
How It Works
-
$unwinddeconstructs the Details array into separate documents -
$lookupjoins with demo102 collection based on PId matching _id -
$projectreplaces PId with the corresponding email using$arrayElemAt -
$groupreconstructs the array structure by grouping back by _id
Conclusion
Use $unwind to flatten arrays, $lookup to join collections, and $group to rebuild the structure. This pipeline effectively replaces array field values with corresponding data from another collection.
Advertisements
