turtle
turtle

Reputation: 8093

Count set of values in MongoDB

I have a MongoDB database with documents that contain a user field. The documents looks like this:

{"_id" : ObjectId("4f98a564590f22a8b13e7df0"), "user" : ['pete', 'joe', 'sally'] ... }

{"_id" : ObjectId("4f981426590f22a8b13e6b62"), "user" : ['tim', 'joe', 'sam'] ... }

How can I construct a query to count the set of all users in my database. For the above two docs, the query would return a count of 5.

Upvotes: 1

Views: 132

Answers (1)

Simeon Visser
Simeon Visser

Reputation: 122516

You can use the distinct() function; it's one of the functions that MongoDB provides to aggregate data:

> db.test.insert({ "user": ["pete", "joe", "sally"]})
> db.test.insert({ "user": ["tim", "joe", "sam"]})
> db.test.find()
{ "_id" : ObjectId("4fb933d5e5d47740efd09ae4"), "user" : [ "pete", "joe", "sally" ] }
{ "_id" : ObjectId("4fb933e9e5d47740efd09ae5"), "user" : [ "tim", "joe", "sam" ] }
> db.test.distinct("user")
[ "joe", "pete", "sally", "sam", "tim" ]
> db.test.distinct("user").length
5

Upvotes: 3

Related Questions