Prashant Shrivastava
Prashant Shrivastava

Reputation: 713

using $group and $match (with range of date) functions in pymongo query

i m trying to execute the following sql query in Mongodb

select organization from users
group by organization 
having 2014-07-10 > date > 2014-07-10

(i dnt knw if SQL syntax is correct or not, but i hope i have given a rough i what i m trying to do here)

first i tried to see how many users were added yesterday

>>> users.find({u"timeCreated":{"$gte":date_yesterday, "$lt":date_today}}).count()
6

now i tried to group the users by the organizations to which they belong and used the following monogo aggregate query

>>> user.aggregate([{'$group':{'_id': "$organization",'count':{"$sum":1}}},{"match":{u'timeCreated':{"$gte":date_yesterday, "$lt":date_today}}}])

result was

{u'ok': 1.0, u'result':[]}

that is no such query.

i even tried using the following query to get all entries dated before today

>>> user.aggregate([{'$group':{'_id': "$organization",'count':{"$sum":1}}},{"match":{u'timeCreated':{"$lt":date_today}}}])

but the output remains the same.

the following command works fine and give a list of organizations

>>> user.aggregate({'$group':{'_id': "$organization",'count':{"$sum":1}}})

can any one tell me where i m going wrng??

P.S. I m new to mongoDB

Upvotes: 0

Views: 651

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151112

The other way around. You want to match the items first

user.aggregate([
   {"$match": {'timeCreated':{ "$gte":date_yesterday, "$lt":date_today } }},
   {'$group':{'_id': "$organization",'count':{"$sum": 1 } }}
])

Also note that as this is a "pipeline" operations like $group or $project are "destructive" and only emit the fields you actually specify.

Upvotes: 1

Related Questions