I have a problem that's been troubling me for a long time and it follows (code demo for example):
from mongoengine import*
Class Scan(Documnet):
name=StringField()
.....
queryset=Scan.objects.filter(name="Bob")
number1=queryset.count()
number2=len(queryset)
However,number1=1782
and number2=1668
, number1 != number2
Anyone can tell me the reason?
This is is due to one of the following reasons as mentioned in the documentation.
On a sharded cluster, db.collection.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:
You can use the aggregate
method to do this as suggested in the documentation.
Scan.aggregate(
{'$group': {
'_id': None,
'count': {'$sum': 1}
}}
)