Saturday, 21 February 2015

mongoDB : $unwind (aggregation)


$unwind deconstructs an array field from the input documents to output a document for each element. Each output document is the input document with the value of the array field replaced by the element.

Syntax
{ $unwind: <field path> }

Let’s say I had document
{"a":1, "b":2, "c" : [1,2,3]}

$unwind on field “c” converts the document as

{"a":1, "b":1, "c":1}
{"a":1, "b":1, "c":2}
{"a":1, "b":1, "c":3}

> db.sample.find()
{ "_id" : 1, "a" : 1, "b" : 2, "c" : [ 1, 2, 3 ] }
>
> db.sample.aggregate([{"$unwind" : "$c"}])
{ "_id" : 1, "a" : 1, "b" : 2, "c" : 1 }
{ "_id" : 1, "a" : 1, "b" : 2, "c" : 2 }
{ "_id" : 1, "a" : 1, "b" : 2, "c" : 3 }


Example
> db.persons.find()
{ "_id" : 1, "name" : "Hari Krishna", "hobbies" : [ "watching movies", "writing blogs", "confuse people" ] }
{ "_id" : 2, "name" : "Kiram Kumar", "hobbies" : [ "eating", "sleeping", "roaming" ] }
{ "_id" : 3, "name" : "ptr", "hobbies" : [ "eating", "watching movies", "confuse people" ] }

Count total number of hobbies

> db.persons.aggregate([{"$unwind" : "$hobbies"}, {"$group": {"_id": "$hobbies", "total" : {"$sum":1}}}])
{ "_id" : "eating", "total" : 2 }
{ "_id" : "roaming", "total" : 1 }
{ "_id" : "confuse people", "total" : 2 }
{ "_id" : "sleeping", "total" : 1 }
{ "_id" : "writing blogs", "total" : 1 }
{ "_id" : "watching movies", "total" : 2 }

 
Prevoius                                                 Next                                                 Home

No comments:

Post a Comment