I have a MongoDB database with documents that look like this:
{"users" : ["u1", "u2", "u3"]}
{"users" : ["u1", "u4"]}
{"users" : ["u1", "u3", "u5", "u6", "u7"]}
I would like to obtain the count of the document with the larger number of users. Using the above, the query would return 5 as the highest user count within the database. How can I do this in MongoDB?
I can get the number of documents with a specific size with:
db.mydb.find({users: {$size: 5}}).count()
However, I can not figure out how to find the largest count within all the documents in the user array.
Thanks.
You can’t do this directly in MongoDB. However, what you can do is have an extra field in the same document called “user_count” and use the $inc operator to increment it by one every time you add a new user to the “users” array.
Your update would look something like: