mongodb - mongodb `$lookup` 或 `join` 与对象数组内的属性
问题描述
我有这个来自 mongodb 的对象
[
{
"_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 的属性,我想用它来加入客户文档,这就是我正在做的事情(在 stackoverflow 的帮助下编写了这段代码:))
const aggregate = await CustomerUnionCustomer.aggregate(
[
{
$match: {migration_customer_union_id: 517}
},
{
$lookup: {
from: 'customers',
localField: 'shaufel_customers.customer',
foreignField: '_id',
as: 'customers',
}
},
{
$project: {
shaufel_customer_union_id: 1,
customerUnion: '$customerUnions',
shaufel_customers: {
$map: {
input: "$customers",
as: "c",
in: {
$mergeObjects: [
"$$c",
{
$arrayElemAt: [{
$filter: {
input: "$shaufel_customers",
cond: {$eq: ["$$this.customer", "$$c._id"]}
}
}, 0]
},
]
}
},
}
}
},
{
"$project": { // this project just to get some specific values inside shaufel_customers
'_id': 0,
"shaufel_customers": {
"$map": {
"input": "$shaufel_customers",
"as": "customer",
"in": {
"customer_id": "$$customer.shaufel_customer_id",
"percent": "$$customer.percent"
}
}
}
}
}
]
)
执行此代码时,我收到以下响应
[
{
"shaufel_customers": [
{
"customer_id": "869",
"percent": 50
}
]
}
]
你可以注意到我得到了一个对象,虽然上面的原始数组中有两个对象,那是因为上面的客户属性具有相同的 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]
},
]
}
},
}
}
},
推荐阅读
- python - 如何在 django 中创建弹出视图?
- angular - 如何使用 Angular 重用 HTML 中的变量
- javascript - 从 v11 迁移后,无法在 discord.js v12 中从服务器设置用户状态和记录用户数量
- c# - C#/.NET Standard 的 Syslog 解析器库
- wordpress - 如何通过特定 ID 的 WordPress 获取用户
- python - How to restrict my dataframe for all the columns values between 0 to 100 in python
- .net - “DataRow”类型中不存在适用的方法“Select”
- ruby-on-rails - rspec 控制器测试无法通过调试控制器
- kdb - 通过仅登记一列创建单行表
- flutter - 在 Flutter 应用中从 pubspec for web 获取版本