1

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}}}])
2
  • Possible duplicate of MongoDB aggregate/group/sum query translated to pymongo query Commented Nov 30, 2016 at 9:44
  • @user3632894 I even tried using pipe as explained in the solution to the question mentioned by you. But either the explanation is too concise or I am making some mistake. Either way, a more detailed solution would be helpful. Commented Nov 30, 2016 at 9:53

1 Answer 1

1

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

It should be {"valid":"1"}

Sign up to request clarification or add additional context in comments.

3 Comments

I knew it was some small error. Thanks for pointing out. I made this mistake while copying this thing from my php code.
Can you explain why do I need to use $ with createdby in db.tme_data.aggregate([{ $match: { valid: 1 } },{"$group": {"_id":"$createdby" , "count":{"$sum":1}}}]?
$ is basically a literal. It provides access to a field. For better understanding refer: docs.mongodb.com/v3.2/reference/operator/aggregation/literal/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.