我有一个包含 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 ,但我的没有分片,它只是一个副本集。
但是,当我聚合
相同的查询并打印总和时,它总是正确的(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"});
最佳答案
第一个查询:
db.collection.count({
"status": "active",
"address.type": "primary",
"address.status": "active"
});
与聚合
的计算方式不同。此选项选择 status = "active"
的所有文档(不是子文档)和 type = "primary"
的 ANY 地址 OR 状态=“Activity ”
。
根据您的问题和评论,我假设您有 1300 个与之匹配的文档,但其中至少有一个与 address.type
和 address.status
不匹配条件位于同一子文档中,因此在将 $unwind
与聚合框架一起使用时返回不同的结果,因为在这种情况下,这两个应该在同一子文档中匹配。
WiredTiger
硬崩溃后出现问题:
作为其他人的引用,另一个不常见的问题是使用 WiredTiger
时发生硬崩溃:
如果您使用WiredTiger作为您的存储引擎,该问题可能是由于硬崩溃导致恢复时 db.stats 状态不一致,即使数据恢复成功,启动后也不会自动重新计算。要重建它们,请运行 db.collection.validate(true)
.
有关此问题的更多信息,请参阅:
关于java - Mongo java 驱动程序 collection.count() 总是返回一个额外的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43865106/