Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

django - mongo:the return don't equal count()

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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}
    }}
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...