HAVING COUNT(column_name) = 1 in mongodb

1,769 views
Skip to first unread message

Niall Paterson

unread,
Oct 9, 2013, 11:34:26 AM10/9/13
to mongod...@googlegroups.com
Hey guys, 

I'm trying to use HAVING COUNT's equivalent  in mongo.

I've tried: 

    messages.aggregate([ { '$match': { count: 1 } } ])   

Which in SQL would be HAVING COUNT(*) = 1 right?

This returns an empty array. Shouldn't that really return every document in messages?

What I really want to do is have something like HAVING COUNT(column_name) = 1 in mongo.

For the sake of this lets say the column_name is conversation_id.

I've tried this but it doesn't work, (which isn't surprising considering the above doesn't even work):

    messages.aggregate([ { '$match': { count: { conversation_id: 1 }  } } } ])

Nobody seems to have done this online, Does anyone know how do I do this kind of thing in mongo?

Many thanks,
Niall

Jeff Lee

unread,
Oct 9, 2013, 12:25:41 PM10/9/13
to mongod...@googlegroups.com
Hey Niall,

You want to use $group with $match.

e.g.

> db.foodle.find()
{ "_id" : 1, "conversation_id" : 1 }
{ "_id" : 2, "conversation_id" : 2 }
{ "_id" : 3, "conversation_id" : 3 }
{ "_id" : 4, "conversation_id" : 1 }
{ "_id" : 5, "conversation_id" : 2 }

> db.foodle.aggregate(
... {$group:{_id:{conversationId:"$conversation_id"}, count:{$sum:1}}},
... {$match:{count:1}})
{
        "result" : [
                {
                        "_id" : {
                                "conversationId" : 3
                        },
                        "count" : 1
                }
        ],
        "ok" : 1
}

See the aggregation examples docs for more examples.



--
--
You received this message because you are subscribed to the Google
Groups "mongodb-user" group.
To post to this group, send email to mongod...@googlegroups.com
To unsubscribe from this group, send email to
mongodb-user...@googlegroups.com
See also the IRC channel -- freenode.net#mongodb
 
---
You received this message because you are subscribed to the Google Groups "mongodb-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mongodb-user...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Niall Paterson

unread,
Oct 9, 2013, 1:53:55 PM10/9/13
to mongod...@googlegroups.com
Amesome, worked perfectly, thanks so much!
Reply all
Reply to author
Forward
0 new messages