json - Project subdocument elements when element name not known in Mongo -
i have json file imported mongo:
{ "people": { "employee1234": { "salary": 10000, "dept": "accounting" }, "employee1235": { "salary": 40000, "dept": "ceo" }, ... } }
i want able find of unique salaries , departments of people.
this tricky because people
aren't in []
id field, rather elements eid. i'm trying equivalent of find({},{people.*.dept})
, can't *
wildcard. how can query (given schema of existing documents) ?
that quite impossible mongodb query current schema have dynamic keys. however, suggest change schema such keys become values , store them in embedded document. schema easy query:
{ "people": [ { "name": "employee1234", "salary": 10000, "dept": "accounting" }, "name": "employee1235", "salary": 40000, "dept": "ceo" } ] }
converting current schema 1 above use native javascript:
db.collection.find().foreach(function(doc){ var people = [], keys = object.keys(doc.people); obj = {}; keys.foreach(function(key){ obj = doc.people[key]; obj.name = key people.push(obj); }); doc.people = people; db.collection.save(doc); });
after changing schema, able query using aggregation framework. aggregation pipeline find of unique salaries , departments of people follows:
db.collection.aggregate([ { "$unwind": "$people" }, { "$group": { "_id": { "salary": "$people.salary", "department": "$people.dept" }, "count": { "$sum": 1 } } }, { "$match": { "count": 1 } } ]);
for above sample document, output be:
/* 0 */ { "result" : [ { "_id" : { "salary" : 40000, "department" : "ceo" }, "count" : 1 }, { "_id" : { "salary" : 10000, "department" : "accounting" }, "count" : 1 } ], "ok" : 1 }
Comments
Post a Comment