MongoDB-2个集合中的$ lookup和$ aggregate

时间:2018-07-13 05:07:26

标签: node.js mongodb aggregation-framework aggregate

我有两个这样的收藏集:

第一个收藏集名称为“促销”:

    {
     "_id": "A019283847466",
     "code": "AAA",
     "aliases" : [ "AAA1","AAA2","AAA3"]
    }

第二个收藏集名称为PromotionUsages:

{
    "customerId": "_1234567890"
    "code": "AAA1"
}
{
    "customerId": "_0987654321"
    "code": "AAA1"
}

预期输出为:

{
    "code": "AAA"
    "aliasCode": "AAA1"
    "countUsages": 2
}

我使用了mongo $ group和$ aggregate,但没有得到所需的输出

请帮忙

谢谢!

2 个答案:

答案 0 :(得分:0)

您可以尝试以下汇总

db.collection.aggregate([
  { "$unwind": "$aliases" },
  { "$addFields": { "aliasesCode": "$aliases" }},
  { "$lookup": {
    "from": PromotionUsages.collection.name,
    "let": { "aliases": "$aliases" },
    "pipeline": [
      { "$match": { "$expr": { "$eq": [ "$code", "$$aliases" ] } } },
      { "$count": "countUsages" }
    ],
    "as": "aliases"
  }},
  { "$unwind": "$aliases" },
  { "$project": { "code": 1, "aliasCode": 1, "countUsages": "$aliases.countUsages" }}
])

输出

{
    "code": "AAA"
    "aliasCode": "AAA1"
    "countUsages": 2
}

答案 1 :(得分:0)

Made some changes in solution suggested by Anthony Winzlet

db.promotions.aggregate([
  { "$unwind": "$aliases" },
  { "$addFields": { "aliasesCode": "$aliases" }},
  { "$lookup": {
    "from": "promotionusages",
    "let": { "aliases": "$aliases" },
    "pipeline": [
      { "$match": { "$expr": { "$eq": [ "$code", "$$aliases" ] } } },
      { "$count": "countUsages" }
    ],
    "as": "aliases"
  }},
  { "$unwind": "$aliases" },
  { "$project": { "_id" : 0,  "code": 1, "aliasesCode": 1, "countUsages": "$aliases.countUsages" }}
])