mongodb`$lookup`或`join`在对象数组中具有属性
我有一个来自mongodb的东西mongodb`$lookup`或`join`在对象数组中具有属性,mongodb,mongoose,aggregate,aggregate-functions,lookup,Mongodb,Mongoose,Aggregate,Aggregate Functions,Lookup,我有一个来自mongodb的东西 [ { "_id": "5eaf2fc88fcee1a21ea0d94d", "migration_customer_union_id": 517, "__v": 0, "account": 1, "createdAt": "2020-05-03T20:55:36.335Z", "customerUnion": "5eaf2fc7698de8321ccd841
[
{
"_id": "5eaf2fc88fcee1a21ea0d94d",
"migration_customer_union_id": 517,
"__v": 0,
"account": 1,
"createdAt": "2020-05-03T20:55:36.335Z",
"customerUnion": "5eaf2fc7698de8321ccd841d",
"shaufel_customers": [
{
"percent": 50,
"_id": "5eaf2fc8698de8321ccd881f",
"customer": "5eaf2fb9698de8321ccd68c0"
},
{
"percent": 50,
"_id": "5eaf2fc9698de8321ccd8a9d",
"customer": "5eaf2fb9698de8321ccd68c0"
}
],
}
]
您可以注意到,在shaufel_customers数组中有一个名为customer的属性,我想用它来连接customers文档,所以我就是这么做的(在stackoverflow的帮助下编写了这段代码:)
当执行此代码时,我得到以下响应
[
{
"shaufel_customers": [
{
"customer_id": "869",
"percent": 50
}
]
}
]
您可以注意到我得到了一个对象,尽管上面的原始数组中有两个对象,这是因为上面的customer属性具有相同的ObjectId值5eaf2fb9698de8321ccd68c0
,这就是我想要问的。即使ID相同,我也希望得到相同的两个对象,因此我在这里期望的结果是
[
{
"shaufel_customers": [
{
"customer_id": "869",
"percent": 50
},
{
"customer_id": "869",
"percent": 50
},
]
}
]
我应该如何做:(您需要还原
$map
并迭代shaufel_customers
,而不是customer
——这将返回两个结果:
{
$project: {
shaufel_customer_union_id: 1,
customerUnion: '$customerUnions',
shaufel_customers: {
$map: {
input: "$shaufel_customers",
as: "sc",
in: {
$mergeObjects: [
"$$c",
{
$arrayElemAt: [{
$filter: {
input: "$customers",
cond: {$eq: ["$$this._id", "$$sc.customer"]}
}
}, 0]
},
]
}
},
}
}
},
成功了!谢谢。你又救了我,谢谢你的帮助。
{
$project: {
shaufel_customer_union_id: 1,
customerUnion: '$customerUnions',
shaufel_customers: {
$map: {
input: "$shaufel_customers",
as: "sc",
in: {
$mergeObjects: [
"$$c",
{
$arrayElemAt: [{
$filter: {
input: "$customers",
cond: {$eq: ["$$this._id", "$$sc.customer"]}
}
}, 0]
},
]
}
},
}
}
},