E
E
Enjoyer2017-05-29 13:08:22
MongoDB
Enjoyer, 2017-05-29 13:08:22

How to count the number of records by query in MongoDB?

Good afternoon!
There is a collection in MongoDB and in some instances there is a required field. Accordingly, in some instances this field is not present. You need to make a request so that only records with the presence of this field appear and you need to calculate how many such records are obtained. I do the query itself like this:
db.getCollection('base').find({'Object1.Object11.String_field' : {"$exists" : true}})
I get the necessary records. And how to calculate their number? I try to add Count() at the end:
db.getCollection('base').find({'Object1.Object11.String_field' : {"$exists" : true}}).count()
It takes a long time and the result is: "The script has completed successful, but nothing to show"
I try to put Count() together with Find() - same result.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
bioGavs, 2017-05-29
@Enjoyer

Try to find records and group, something like this
res = db.getCollection('base').aggregate([
{'$match': {'Object1.Object11.String_field': {"$exists" : true}}} ,
{'$group': {'_id': {'$sum': 1}}
])
count = res['_id']
Or even simpler
https://docs.mongodb.com/manual/reference/operator ...

L
lega, 2017-05-29
@lega

Works for a long time and the result is nothing"
Change the structure so that it works quickly, by index, instead of "empty value" write null.
Otherwise, you might as well write to a text file and complain further.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question