Monday, 15 April 2013

node.js - How to get distinct value of sub document field with their count in collection in mongodb? -



node.js - How to get distinct value of sub document field with their count in collection in mongodb? -

i have collection documents below.i want distinct value of name of attributes sub-document distinct value , count in collection.

example :

var records = [ { "attributes": [ { "name": "color", "value": "black", "_id": "5441103a0348ebc91ee75b33" } ], "name": "ddd" }, { "attributes": [ { "name": "color", "value": "red", "_id": "5441091393450f1619be99af" }, { "name": "size", "value": "l", "_id": "5441091393450f1619be99b0" } ], "name": "one" }, { "attributes": [ { "name": "color", "value": "black", "_id": "5441092593450f1619be99b1" }, { "name": "size", "value": "l", "_id": "5441092593450f1619be99b2" } ], "name": "sdfsda" }, { "attributes": [ { "name": "color", "value": "green", "_id": "5441093d93450f1619be99b3" }, { "name": "size", "value": "s", "_id": "5441093d93450f1619be99b4" } ], "name": "threee" }, { "attributes": [ { "name": "color", "value": "green", "_id": "5441095793450f1619be99b5" }, { "name": "size", "value": "m", "_id": "5441095793450f1619be99b6" } ], "name": "one" } ]

i want output :

var output = { "color" : [ {value : 'red', count : 1} {value : 'black', count : 2} {value : 'green', count : 2} ], "size" : [ {value : 's', count : 2} {value : 'l', count : 1} {value : 'm', count : 1} ] }

how can output in mongodb?

can output aggregate framework of mongodb, if yes, how? -- high priority

yes, aggregate can create it.

var output = {}; db.c.aggregate([{ $unwind : "$attributes" }, { $group : { _id : { name : "$name", value : "$value" }, count : { $sum : 1 } } // output after stage such // {_id:{name:"color", value:"green"}, count:2} // {_id:{name:"size", value:"s"}, count:2} }, { $group : { _id : "$_id.name", contents : { $push : { value : "$_id.value", count : "$count" } } } // output after stage such // {_id:"color", contents:[{value:"green", count:2}]} // {_id:"size", contents:[{value : 's', count : 2}]} }]).foreach(function(doc) { output[doc._id] = doc.contens; // convert format expected });

node.js mongodb

No comments:

Post a Comment