Reputation: 143
I tried to map two collections its working fine but I have doubt in how to rename the column name using mongodb.
promotion collection
{
"_id" : ObjectId("5cf7679a0b0bed2e7483b998"),
"group_name" : "Latest",
"products" :
[ObjectId("5cecc161e8c1e73478956333"),ObjectId("5cecc161e8c1e73478956334")]
}
product collection
{
"_id" : ObjectId("5cecc161e8c1e73478956333"),
"product_name" : "bourbon"
},
{
"_id" : ObjectId("5cecc161e8c1e73478956334"),
"product_name" : "bour"
}
mapping query
db.promotional.aggregate(
[
{
$lookup: {
from: "product",
localField: "products",
foreignField: "_id",
as: "products"
}
},
{
$project :{products :{_id:0}}
}
]
)
I got output
{
"_id" : ObjectId("5cf7679a0b0bed2e7483b998"),
"group_name" : "Latest",
"products" :
[
{
"product_name" : "bourbon"
},
{
"product_name" : "bour"
}
]
}
Expected output
{
"_id" : ObjectId("5cf7679a0b0bed2e7483b998"),
"group_name" : "Latest",
"products" :
[
{
"name" : "bourbon"
},
{
"name" : "bour"
}
]
}
How to rename productname to name using mongodb
Upvotes: 1
Views: 491
Reputation: 46461
You can $map
over the products
array and can change the fields name
db.promotional.aggregate([
{ "$lookup": {
"from": "product",
"localField": "products",
"foreignField": "_id",
"as": "products"
}},
{ "$addFields": {
"products": {
"$map": {
"input": "products",
"as": "product",
"in": {
"name": "$$product.product_name"
}
}
}
}}
])
If you are using mongodb version 3.6 and above
db.promotional.aggregate([
{ "$lookup": {
"from": "product",
"let": { "products": "$products" },
"pipeline": [
{ "$match": { "$expr": { "$in": [ "$_id", "$$products" ] } } },
{ "$project": { "name": "$product_name", "_id": 0 }}
],
"as": "products"
}}
])
Upvotes: 1