我有两个这样的收藏:

第一个收藏名称是Promotions:

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


2nd Collection名称为PromotionUsages:

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


预期输出为:

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


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

任何帮助请

谢谢!!!

最佳答案

您可以尝试以下汇总

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
}

关于node.js - MongoDB-2个集合中的$ lookup和$ aggregate,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51317983/

10-12 19:48