Reputation: 91
I would like to convert this type of document (objects in array):
[{"name": "david", "props": {"prop1": {"AR": 9, "NY": 8}, "prop2":
{"AR": 10, "NY": 9}}},
{"name": "john", "props": {"prop1": {"AR": 7, "NY": 8}, "prop2": {"AR":
8, "NY": 9}}}]
into this one (filtering by the 'AR' field):
{"david": {"prop1": 9, "prop2": 10}, "john": {"prop1": 7, "prop2": 8}}
using MongoDB aggregations. Any thoughts?
Upvotes: 1
Views: 367
Reputation: 49975
There are two really helpful operators: $objectToArray which converts an object into an array of k-v
pairs and $arrayToObject which converts that array back to an object. So you should use first one, reshape your objects and then use second one. So having a document like this:
{
array: [
{"name": "david", "props": {"prop1": {"AR": 9, "NY": 8}, "prop2": {"AR": 10, "NY": 9}}},
{"name": "john", "props": {"prop1": {"AR": 7, "NY": 8}, "prop2": {"AR": 8, "NY": 9}}}
]
}
You can use below aggregation:
db.col.aggregate([
{
$project: {
output: {
$arrayToObject: {
$map: {
input: "$array",
as: "doc",
in: {
k: "$$doc.name",
v: {
$arrayToObject: {
$map: {
input: { $objectToArray: "$$doc.props" },
as: "prop",
in: { k: "$$prop.k", v: "$$prop.v.AR" }
}
}
}
}
}
}
}
}
}
])
Which outputs:
{ "_id" : ..., "output" : { "david" : { "prop1" : 9, "prop2" : 10 }, "john" : { "prop1" : 7, "prop2" : 8 } } }
Upvotes: 1