mongodb 聚合函数并根据条件返回结果

时间:2021-01-15 10:58:51

标签: mongodb aggregation

我有两张表 vendor 和 vendorgs。 我的情况如下, 1.vendors表vendorOrgId === vendorgs表_id 2.status === "active" 在 vendorgs 表中 如果满足上述条件,则按 vendorgs 表类别对供应商进行分组。 可以这样做

供应商表

const vendors = [{
  "name" : "Alfred",
  "location" : "FH",
  "vendorOrgId" : "1"
},
{
  "name" : "Alfred",
  "location" : "ADH",
  "vendorOrgId" : "2"
},
{
  "name" : "Alfred",
  "location" : "AFF",
  "vendorOrgId" : "41"
}]

供应商表


const vendorgs = [
  {
    "orgName" : "star super market",
    "_id" : "1",
    "category" : "grocery",
    "status" : "active"
  },
  {
    "orgName" : "L.f super market",
    "_id" : "41",
    "category" : "grocery",
    "status" : "active"
  },
  {
    "orgName" : "Fresh mart",
    "_id" : "2",
    "category" : "Milk",
    "status" : "active"
  }
]

我的查询

db.getCollection('vendors').aggregate([{
        "$lookup": {
            "from": "vendorgs",
            "localField": "vendorOrgId",
            "foreignField": "_id",
            "as": "data"
        },
    },
     {
        "$group": {
            "_id": "$data.category",
            "category":{"$push":"$data"},

        }
    },
{
        "$match": {
            "category.status":true
        }
    }
])

上面的查询返回空数组

预期结果

{
    "grocery": [{
            "name": "Alfred",
            "location": "FH",
            "vendorOrgId": "1"
        },
        {
            "name": "Alfred",
            "location": "AFF",
            "vendorOrgId": "41"
        }
    ],
    "milk": [{
        "name": "Alfred",
        "location": "ADH",
        "vendorOrgId": "2"
    }]
}

谢谢!!

1 个答案:

答案 0 :(得分:0)

终于在自己身上找到了答案。应该在 group by 之前写 match

db.getCollection('vendors').aggregate([{
        "$lookup": {
            "from": "vendorgs",
            "localField": "vendorOrgId",
            "foreignField": "_id",
            "as": "data"
        },
    },
{
        "$match": {
            "status":"active"
        }
    },
     {
        "$group": {
            "_id": "$data.category",
            "category":{"$push":"$data"},

        }
    }
])