Anubhav Anubhav - 11 days ago 5
Python Question

Python - Aggregation of MongoDB with "match" condition

I'm trying to get a count of a value in my collection. Here's a sample:

{
"_id" : ObjectId("583e86987f22def116c35055"),
"createdby" : "DEO007",
"valid" : 1
}


In each document, some "valid" are 0 and some are 1.
In my case, I only want the total count of documents grouped by "createdby" which has "valid" : 1.

I tried this in MongoDB and it worked without any error :

db.tme_data.aggregate([{ $match: { valid: 1 } },{"$group": {"_id":"$createdby" , "count":{"$sum":1}}}])


But I'm not able to implement the same in my python code.
This is what I tried :

collection.aggregate([{"$match":{"$valid":"1"}}, {"$group": {"_id":"$createdby" , "count":{"$sum":1}}}])


It gave me a blank collection.

PS:

1) I'm using pymongo

2) This is working properly in my python code :

collection.aggregate([{"$group": {"_id":"$createdby" , "count":{"$sum":1}}}])

Answer

Why do you have {"$valid":"1"} in your python code. Its a field to be matched. It should be {"valid":"1"}