mongodb聚合管道合并两个都需要$ match条件的集合

时间:2018-09-12 21:27:03

标签: mongodb aggregation-framework

您好,我有两个集合(产品和订单),并且正在尝试创建一个汇总,该汇总将导致针对特定供应商列出的所有产品,并将特定订单中的数量附加到数据中(如果订单包含该数量)其中的特定产品。

Product Collection

{
    _id: objectId,
    supplierId: objectId1,          // supplier 1
    sku: "prod1"
},
{
    _id: objectId,
    supplierId: objectId1,          // supplier 1
    sku: "prod2"
},
{
    _id: objectId,
    supplierId: objectId1,          // supplier 1
    sku: "prod3"
}
{
    _id: objectId,
    supplierId: objectId2,          // supplier 2
    sku: "prod4"
},
{
    _id: objectId,
    supplierId: objectId2,          // supplier 2
    sku: "prod5"
}

Order Collection

{
    _id: objectId5      // order 1
    product: [{
        _id: objectId,
        supplierId: objectId1,
        sku: prod1,
        qty: 5

    },
    {
        _id: objectId,
        supplierId: objectId1,
        sku: prod2,
        qty: 1
    }]
},
{
    _id: objectId6      // order 2
    product: [{
        _id: objectId,
        supplierId: objectId1,
        sku: prod1,
        qty: 100

    }, ...
    ]
}


result should be

{
    _id: objectId,
    supplierId: objectId1,      // supplier 1
    sku: "prod1",
    qty: 5
},
{
    _id: objectId,
    supplierId: objectId1,      // supplier 1
    sku: "prod2",
    qty: 1
},
{
    _id: objectId,
    supplierId: objectId1,      // supplier 1
    sku: "prod3",
    qty: 0 || null
}

我的尝试还不算很远,但是记下了一些伪代码来说明我的问题所在。我毫不怀疑在这里只需要做些什么,但是任何帮助将不胜感激。

  product.aggregate([{$match: {supplierId: objectId1}},
     {$lookup: {join order collection but only where orderId: objectId5}},
     {$projection: {append qty where there is one append to each product that matches.  prodcuts that don't match append 0 or null}}
    ])

1 个答案:

答案 0 :(得分:0)

您可以尝试在3.6版本的$lookup管道下面进行聚合。

$ lookup管道

db.products.aggregate([
  {"$match":{"supplierId":objectId1}},
  {"$lookup":{
    "from":"orders",
    "let":{"supplierId":"$supplierId","sku": "$sku"},
    "pipeline":[
      {"$match":{"_id":objectId5, "$expr":{"$and":[{"$in":["$$supplierId","$product.supplierId"]},{"$in":["$$sku","$product.sku"]}]}}},
      {"$unwind":"$product"},
      {"$match":{"$expr":{"$and":[{"$eq":["$$supplierId","$product.supplierId"]},{"$eq":["$$sku","$product.sku"]}]}}}       
    ],
    "as":"mproduct"
  }},
 {"$replaceRoot":{"newRoot":{"$mergeObjects":["$$ROOT",{"$cond":[{"$ne":["$mproduct",[]]},{"qty":{"$arrayElemAt":["$mproduct.product.qty",0]}},{"qty":0}]}]}}},
 {"$project":{"mproduct":0}}
])