Merge/Combine 来自不同领域的两个对象数组
Merge/Combine two object arrays from different fields
我有一个数组 in_cart 其中有 product_id(s) 和购物车文档中各个项目的 数量
"in_cart":[
{
"product_id":"12345",
"amount":2
}
]
我想要做的是将金额字段插入到详细信息数组。 $lookup 运算符在 product_id 上完成,因此两个数组中的项目数量总是相等的。
"details":[
{
"_id":"12345",
"name":"test",
"price":1110,
// ...more data...
}
]
$map
遍历 details 数组。
$filter
从in_cart数组中过滤掉product_id[=的文档29=] 字段作为 details 数组中的当前项在 _id 字段 中
$arrayElemAt
获取过滤后数组的第一个元素(因为它总是只有一个元素)
$getField
只得到 数量 属性 的过滤项目
db.collection.aggregate([
{
$set: {
details: {
$map: {
input: "$details",
in: {
_id: "$$this._id",
name: "$$this.name",
price: "$$this.price",
amount: {
$getField: {
field: "amount",
input: {
$arrayElemAt: [
{
$filter: {
input: "$in_cart",
as: "cart_item",
cond: {
$eq: [
"$$cart_item.product_id",
"$$this._id"
]
}
}
},
0
]
}
}
}
}
}
}
}
}
])
我有一个数组 in_cart 其中有 product_id(s) 和购物车文档中各个项目的 数量
"in_cart":[
{
"product_id":"12345",
"amount":2
}
]
我想要做的是将金额字段插入到详细信息数组。 $lookup 运算符在 product_id 上完成,因此两个数组中的项目数量总是相等的。
"details":[
{
"_id":"12345",
"name":"test",
"price":1110,
// ...more data...
}
]
$map
遍历 details 数组。$filter
从in_cart数组中过滤掉product_id[=的文档29=] 字段作为 details 数组中的当前项在 _id 字段 中
$arrayElemAt
获取过滤后数组的第一个元素(因为它总是只有一个元素)$getField
只得到 数量 属性 的过滤项目
db.collection.aggregate([
{
$set: {
details: {
$map: {
input: "$details",
in: {
_id: "$$this._id",
name: "$$this.name",
price: "$$this.price",
amount: {
$getField: {
field: "amount",
input: {
$arrayElemAt: [
{
$filter: {
input: "$in_cart",
as: "cart_item",
cond: {
$eq: [
"$$cart_item.product_id",
"$$this._id"
]
}
}
},
0
]
}
}
}
}
}
}
}
}
])