ricsh
ricsh

Reputation: 63

MongoDB unique count

Hi I will try to give a simple example of what I am trying to achieve, I've tried using the aggregation pipeline and distinct but I am a bit lost

I have the following records

item1 - A : "xxxx", U : "1111"
item2 - A : "xxxx", U : "2222"
item3 - A : "bbbb", U : "1111"
item4 - A : "bbbb", U : "3333"
item4 - A : "xxxx", U : "3333"

I am trying to write a query which will give me a unique count of U where U has a record which match A = "xxxx" and A = "bbbb"

so the above case the count would be 2 as there is only two users who has a record for bbbb and xxxx

Upvotes: 1

Views: 124

Answers (1)

Alex V
Alex V

Reputation: 1155

What about using aggregation? Original data:

> db.items.find({}, {_id: 0})
{ "A" : "xxxx", "U" : "1111" }
{ "A" : "xxxx", "U" : "2222" }
{ "A" : "bbbb", "U" : "1111" }
{ "A" : "bbbb", "U" : "3333" }
{ "A" : "xxxx", "U" : "3333" }

Aggregation query:

> db.items.aggregate([{$group: {_id: '$U', alist: {$push: '$A'}}}, {$match: {alist: {$all: ['bbbb', 'xxxx']}}}])
{ "_id" : "3333", "alist" : [ "bbbb", "xxxx" ] }
{ "_id" : "1111", "alist" : [ "xxxx", "bbbb" ] }

Upvotes: 1

Related Questions