我有一个名为 A 的集合,其中有一个产品数组, 我有一个集合 B,它也有一个产品数组,A 和 B 关系是通过 _id 一对多,对于 A 中的每个文档,B 中可能有多个文档,而且 B 的产品数组仅包含 A 的产品数组中的产品。
这是集合A
{
"_id": "abcdefg",
"products": [
{
"_id": "1",
"_product": "1",
"quantity": 12
},
{
"_id": "2",
"_product": "2",
"quantity": 32
},
{
"_id": "3",
"_product": "3",
"quantity": 12
}
]
}
这是 B 中的两个文档 文件1
{
"_id": "<<obj_id>>",
"A_id":"abcdefg",
"products": [
{
"_id": "<<_id>>",
"_product": "1",
"quantity": 6
},
{
"_id": "<<_id>>",
"_product": "2",
"quantity": 16
}
]
}
和文档 2
{
"_id": "<<obj_id>>",
"A_id":"abcdefg",
"products": [
{
"_id": "1",
"_product": "1",
"quantity": 6
},
{
"_id": "2",
"_product": "2",
"quantity": 12
},
{
"_id": "3",
"_product": "3",
"quantity": 8
}
]
}
现在,我需要一个管道/策略,在其中我可以获得 A 的产品和(所有 B'产品的总和)的数量差异,其中产品的 id 相等,即类似这样
[
0,
4,
4
]
最佳答案
经过2个小时的磨练,终于可以工作了。
db.collectionb.aggregate([
{
$unwind: "$products"
},
{
$lookup:{
from:"collectiona",
localField:"A_id",
foreignField:"_id",
as:"colaref"
}
},
{
$unwind: "$colaref"
},
{
$unwind:"$colaref.products"
},
{
$project:{
colaProducts:"$colaref.products",
products:"$products",
idEq:{ $eq:["$colaref,products._id","$products._id"]}
}
},
{
$match:{
idEq: true
}
},
{
$project:{
quantity:{
$subtract:["$colaProducts.quantity","$products.quantity"]
}
}
}
])
如果我添加 CollectionB 文档 ID 的匹配项,那么我会得到一些我想要的结果。
关于node.js - 将集合中文档的属性减去不同集合中另一个文档的属性,并返回差值数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52315323/