MongoDb 聚合 $lookup 和 $project
MongoDb aggregation $lookup and $project
我刚刚遇到了一个有趣的聚合管道问题。因为我是新手,所以我随机尝试了一些东西,但没有得到想要的输出。希望大家帮我解决!
我有两个collection,
collection一个=>
{
_id: 1,
field1: "value1",
field2: "value2
}
collection b=>
{
_id: 101,
collectionAId: 1,
status: "active"
},
{
_id: 102,
collectionAId: 1,
status: "inactive"
},
{
_id: 102,
collectionAId: 1,
status: "expired"
}
我的目标是
{
_id: 1,
field1: "value1",
field2: "value2,
status: ["active", "inactive", "expired"]
}
您可以使用 $map
结合 $project
:
来实现
db.a.aggregate([
{
"$lookup": {
"from": "b",
"localField": "_id",
"foreignField": "collectionAId",
"as": "output"
}
},
{
"$project": {
field1: 1,
field2: 1,
status: {
"$map": {
"input": "$output",
"as": "v",
"in": "$$v.status"
}
}
}
}
])
我刚刚遇到了一个有趣的聚合管道问题。因为我是新手,所以我随机尝试了一些东西,但没有得到想要的输出。希望大家帮我解决!
我有两个collection,
collection一个=>
{
_id: 1,
field1: "value1",
field2: "value2
}
collection b=>
{
_id: 101,
collectionAId: 1,
status: "active"
},
{
_id: 102,
collectionAId: 1,
status: "inactive"
},
{
_id: 102,
collectionAId: 1,
status: "expired"
}
我的目标是
{
_id: 1,
field1: "value1",
field2: "value2,
status: ["active", "inactive", "expired"]
}
您可以使用 $map
结合 $project
:
db.a.aggregate([
{
"$lookup": {
"from": "b",
"localField": "_id",
"foreignField": "collectionAId",
"as": "output"
}
},
{
"$project": {
field1: 1,
field2: 1,
status: {
"$map": {
"input": "$output",
"as": "v",
"in": "$$v.status"
}
}
}
}
])