将集合中文档的属性减去另一个集合中另一个文档的属性,并返回差异数组

时间:2018-09-13 13:55:37

标签: node.js mongodb mongoose aggregation-framework pipeline

我有一个名为A的集合,其中有一个产品数组, 我有一个集合B,它也有一个产品数组,通过_id,A和B关系是一对多的,对于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中的两个文档 Doc 1

{
"_id": "<<obj_id>>",
"A_id":"abcdefg",
"products": [
    {
        "_id": "<<_id>>",
        "_product": "1",
        "quantity": 6
    },
    {
        "_id": "<<_id>>",
        "_product": "2",
        "quantity": 16
    }
]
}

和DOC 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
]

1 个答案:

答案 0 :(得分:0)

经过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添加一个匹配项,那么我会得到想要的东西。

相关问题