Reputation: 6036
Well, I have documents with this strcuture:
{
"x" : "X1",
"y" : 10
},
{
"x" : "X2",
"y" : 22
},
{
"x" : "...",
"y" : 42
}
So, how I can convert all results to:
{
"X1" : 10,
"X2" : 22,
"X3" : 42
}
I trying with $arrayToObject
and $map
, but this dont work
Thanks!
This collection have arround 50 millions docs.
Upvotes: 0
Views: 119
Reputation: 49945
Assuming your collection is small enough so that an output of following operation won't exceed 16MB BSON limit, you can use below aggregation:
db.col.aggregate([
{
$group: {
_id: null,
docs: {
$push: {
k: "$x",
v: "$y"
}
}
}
},
{
$replaceRoot: {
newRoot: {
$arrayToObject: "$docs"
}
}
}
])
$arrayToObject expects objects having two properties k
and v
. To promote that object to a root level you can use $replaceRoot operator.
Upvotes: 1