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?
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.
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.
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}}}
])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With