Mongodb上的聚合过滤器和查找

时间:2017-05-24 03:52:43

标签: mongodb mongodb-query aggregation-framework

我的第一个集合employeecategory如下所示;

[{
    name: "GARDENING"
  },
  {
    name: "SECURITY"
  },
  {
    name: "PLUMBER"
  }
]

我的第二个集合complaints如下所示;

[{
  communityId: 1001,
  category: "SECURITY",
  //other fields
}, {
  communityId: 1001,
  category: "GARDENING",
  //other fields
}]

我正在尝试加入上表并获得以下结果;

[{
  "count": 1,
  "name": "GARDENING"
}, {
  "count": 1,
  "name": "SECURITY"
}, {
  "count": 0,
  "name": "PLUMBER"
}]

即使集合2中没有记录,我也需要数。我尝试了以下聚合,但没有奏效。如果我删除匹配条件它正在工作,但我需要过滤社区ID。有些人可以建议最好的方法来实现这一目标。 Mongo DB版本是3.4.0

db.employeecategory.aggregate(
  [{
    $match: {
      "complaints.communityId": 1001
    }
  }, {
    "$lookup": {
      from: "complaints",
      localField: "name",
      foreignField: "category",
      as: "embeddedData"
    }
  }]
)

1 个答案:

答案 0 :(得分:0)

在单个聚合中,无法实现communityId = 1001的过滤和分组而不会丢失count = 0类别。执行此操作的方法首先从complaints集合开始,并过滤communityId = 1001个对象,并使用它创建临时集合。然后从employeecategory集合,$lookup加入该临时集合,$group加入name,此时您将获得结果,然后删除临时表。< / p>

// will not modify complaints document, will create a filtered temp document
db.complaints.aggregate(
  [{
      $match: {
        communityId: 1001
      }
    },
    {
      $out: "temp"
    }
  ]
);

// will return the answer that is requested by OP
db.employeecategory.aggregate(
  [{
    $lookup: {
      from: "temp",
      localField: "name",
      foreignField: "category",
      as: "array"
    }
  }, {
    $group: {
      _id: "$name",
      count: {
        $sum: {
          $size: "$array"
        }
      }
    }
  }]
).pretty();

db.temp.drop(); // to get rid of this temporary collection

会结果;

{ _id: "PLUMBER", count: 0},
{ _id: "SECURITY", count: 2},
{ _id: "GARDENING", count: 1}

我所拥有的测试数据;

db.employeecategory.insertMany([
   { name: "GARDENING" },
   { name: "SECURITY" },
   { name: "PLUMBER" }
]);

db.complaints.insertMany([
   { category: "GARDENING", communityId: 1001 },
   { category: "SECURITY", communityId: 1001 },
   { category: "SECURITY", communityId: 1001 },
   { category: "SECURITY", communityId: 1002 }
]);