【发布时间】:2017-05-09 08:43:14
【问题描述】:
我有 2 个节点的 MongoDB 副本集。
集合中的典型文档如下所示:
{
_id: 409,
status: "active"
address: [
{ id: 1000012, type: "primary", status: "active" },
{ id: 1000011, type: "primary", status: "inactive" },
{ id: 1000010, type: "primary", status: "inactive" }
],
}
当我使用 Java MongoDB Driver 来查找集合的计数时,基于一些简单的过滤器,我总是会得到 1 个额外的(例如,如果实际计数是 1299,则结果是 1300):
db.collection.count({
"status": "active",
"address.type": "primary",
"address.status": "active"
});
我在官方文档中看到collection.count(...)can return incorrect results in case of sharded collections,但是我的没有分片,它只是一个副本集。
但是,当我aggregate 相同的查询并打印总和时,它总是正确的(1299):
db.collection.aggregate([
{ $unwind: "$address" },
{ $match: {
"status": "active",
"address.type": "primary",
"address.status": "active",
}},
{ $group: { _id: null, count: { $sum: 1 }}},
{ $project: { _id: 0, count: 1 }}
]);
这种行为的原因可能是什么?
这匹配聚合:
db.collection.count({"address": {$elemMatch:{"status": "active", "type": "primary"}}, status: "active"});
【问题讨论】:
标签: java mongodb aggregation-framework