Group Document By Array Field Index In Mongodb
Posted By : Pankaj Kumar Yadav | 29-Sep-2017
Hi All,
In this blog, I'm going to describe group documents by array field’s index in Mongodb. Grouping in mongodb is a very easy because mongodb provides many expressions for grouping documents. For more click here. Mongodb is a document oriented database and provides more flexibility in compare to Relational database. Mongodb group expression is $group and has following prototype form:
{ $group: { _id: <expression>, <field1>: { <accumulator1> : <expression1> }, ... } }
The _id field is required. If we don't want we can set it as null. We can set _id as null to calculate accumulated values for all the input documents as a whole. Suppose we have collection named start_of_the_month and start_of_the_month has an array type field winners :
{ "_id" : ObjectId("59cdf733c01b9bbe0c144522"), "winners" : [ "Jack", "Alex", "John" ] }
{ "_id" : ObjectId("59cdf746c01b9bbe0c144523"), "winners" : [ "William", "Jack", "Alex", "John" ] }
{ "_id" : ObjectId("59cdf756c01b9bbe0c144524"), "winners" : [ "Rose", "Alex", "John" ] }
{ "_id" : ObjectId("59cdf75ec01b9bbe0c144525"), "winners" : [ "Jack", "Rose", "Alex", "John" ] }
Now we want to group by winners name who came first and how many times he came. Result will be like Jack won 2 times, Rose won 1 time and William won 1 time.
db.start_of_the_month.aggregate([{
"$group": {
"_id": {
"$arrayElemAt": ["$winners", 0]
},
won: {
"$sum": 1
}
}
}]);
the result will be like:
{ "_id" : "Rose", "won" : 1 }
{ "_id" : "William", "won" : 1 }
{ "_id" : "Jack", "won" : 2 }
As we can see the Jack won 2 times, Rose won 1 time and William won 1 time.
Thanks
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Pankaj Kumar Yadav
Pankaj has been working as a Grails developer expertise in struts, spring, ejb, hibernate and angularjs framework.