Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count field values with more than one occurence in mongodb

i have a collection like

_id: ObjectId("568f93b5e0ce9f35377c723e")
 rollNo: "123"

 _id: ObjectId("568f93b5e0ce9f35377c723g")
 rollNo: "111"

 _id: ObjectId("568f93b5e0ce9f35377c723g")
 rollNo: "123"

i want to query and get the count of distinct roll nos. For eg from my above collection i should get the count as 2. and i also i would like to print the roll nos whose occurrence is more than one for eg from my above collection roll no 123 should be printed.

I tried with

db.student.aggregate([
    { "$group": {
        "_id": "$rollNo",
        "count": { "$sum": 1 }
    }}
],function(err,result) {

});

this will print every roll number followed by its count. My collection is very huge and hence its difficult to track . Is there any other simpler way i can achieve this?

like image 892
Shaik Mujahid Ali Avatar asked Jan 11 '16 08:01

Shaik Mujahid Ali


People also ask

How do I search for multiples in MongoDB?

MongoDB provides the find() that is used to find multiple values or documents from the collection. The find() method returns a cursor of the result set and prints all the documents. To find the multiple values, we can use the aggregation operations that are provided by MongoDB itself.

Can we use count with aggregate function in MongoDB?

MongoDB $count AggregationThe MongoDB $count operator allows us to pass a document to the next phase of the aggregation pipeline that contains a count of the documents. There a couple of important things to note about this syntax: First, we invoke the $count operator and then specify the string.


1 Answers

In order to get the count of distinct field you can take advantage of distinct command which returns an array of distinct values for a field; you can check the length of the array for a count.

db.student.distinct("rollNo").length

In order to print the roll nos whose occurrence is more than one you can take advantage of $match operator after grouping:

db.student.aggregate([     
    {"$group": {"_id": "$rollNo", "count": { "$sum": 1 }}}, 
    {"$match": {count: {"$gt": 1}}} 
])
like image 101
Volodymyr Synytskyi Avatar answered Sep 30 '22 10:09

Volodymyr Synytskyi