我有一个包含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"});
答案 0 :(得分:1)
第一个查询:
db.collection.count({
"status": "active",
"address.type": "primary",
"address.status": "active"
});
与aggregation
的计算方法不同。这个是选择status = "active"
和 ANY 地址的所有文档(不是子文档),type = "primary"
或 status = "active"
。
根据您的问题和评论,我假设您有1300个与之匹配的文档,但其中至少有一个文档与同一子文档中的address.type
和address.status
条件不匹配,因此返回将$unwind
与聚合框架一起使用时的结果不同,因为在这种情况下,这两个应该在同一子文档中匹配。
WiredTiger
问题:
作为其他人的参考,使用WiredTiger
时,另一个不常见的问题是严重崩溃:
如果您使用WiredTiger作为存储引擎,则问题可能是由于硬件崩溃导致恢复时db.stats
状态不一致,启动后不会自动重新计算,甚至虽然数据已成功恢复。要重建它们,请运行db.collection.validate(true)
。
有关此问题的更多信息,请参阅: