On a sharded cluster, count can result in an inaccurate count if orphaned documents exist or if a chunk migration is in progress.
To avoid these situations, on a sharded cluster, use the $group stage of the db.collection.aggregate() method to $sum the documents. For example, the following operation counts the documents in a collection:
db.collection.aggregate(
[
{ $group: { _id: null, count: { $sum: 1 } } }
]
)
To get a count of documents that match a query condition, include the $match stage as well:
db.collection.aggregate(
[
{ $match: <query condition> },
{ $group: { _id: null, count: { $sum: 1 } } }
]
)
参见文档:https://docs.mongodb.com/manual/reference/command/count/
网友评论