Create MongoDB fields with names based on sub-document values using aggregation pipeline? -
given mongodb collection following document structure:
{ array_of_subdocs: [ { animal: "cat", count: 10 }, { animal: "dog", count: 20 }, ... ] }
where each document contains array of sub-documents, want transform collection documents of structure:
{ cat: { count: 10 }, dog: { count: 20 }, ... }
where each sub-document value of new field in main document named after 1 of values within sub-document (in example, values of animal
field used create name of new fields, i.e. cat
, dog
).
i know how eval
javascript snippet. it's slow. question is: how can done using aggregation pipeline?
according this feature request , solution, new feature added functionality - function called arraytoobject
.
db.foo.aggregate([ {$project: { array_of_subdocs: { $arraytoobject: { $map: { input: "$array_of_subdocs", as: "pair", in: ["$$pair.animal", "$$pair.count"] } } } }} ])
but @ moment, no solution. suggest change data structure. far see there many feature requests labeled major not done years.
Comments
Post a Comment