mongodb 聚合函数和 return 基于条件的结果

mongodb aggregate function and return the result based on the condition

我有两个 tables 供应商和供应商。 我的情况如下, 1.vendors table vendorOrgId === vendorgs table _id 2.status === 在 vendorgs table 中“活跃” 如果满足上述条件,则按 vendorgs table 类别对供应商进行分组。 可以做到吗

供应商table

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

供应商table


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"
    }]
}

谢谢!!

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

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

        }
    }
])