How to do HAVING COUNT in MongoDB? -
my documents this:
{ "_id": objectid("5698fcb5585b2de0120eba31"), "id": "26125242313", "parent_id": "26125241841", "link_id": "10024080", "name": "26125242313", "author": "gigaquack", "body": "blogging = creative writing", "subreddit_id": "6", "subreddit": "reddit.com", "score": "27", "created_utc": "2007-10-22 18:39:31" }
what i'm trying create query finds users posted 1 subreddit. did in sql using query:
select distinct author, subreddit reddit group author having count(*) = 1;
i'm trying similar in mongodb having troubles atm. managed recreate select distinct using aggregate group can't figure out how solve having count part.
this query looks like:
db.collection.aggregate( [{"$group": { "_id": { author: "$author", subreddit: "$subreddit" } } }, {$match:{count:1}} // part not working ])
am using $match wrong?
your query should like:
db.collection.aggregate([{ '$group': { '_id': {'author': '$author', 'subreddit': '$subreddit'}, 'count': {'$sum': 1}, 'data': {'$addtoset': '$$root'}} }, { '$match': { 'count': {'$eq': 1} }}])
where data one-length list matched document.
if want exact field, should this:
db.collection.aggregate([{ '$group': { '_id': {'author': '$author', 'subreddit': '$subreddit'}, 'count': {'$sum': 1}, 'author': {'$last': '$author'}} }, { '$match': { 'count': {'$eq': 1} }}])
Comments
Post a Comment