In mongodb I have a document of structure:
{
"phone":"123",
"friends": {
"contacts":{
"234":2,
"345":5
}
}
}
I want the output to look like :
{
"123": {
"234":2,
"345":5
}
}
I have search for multiple solution. Don't seem like getting a solution.
You can use $arrayToObject to create custom keys (takes an array of k-v
pairs as a parameter) and then you can use $replaceRoot to get custom root object, try:
db.collection.aggregate([
{
$match: {
phone: { $exists: true },
"friends.contacts": { $exists: true }
}
},
{
$addFields: {
array: [{
k: "$phone",
v: "$friends.contacts"
}]
}
},
{
$replaceRoot: {
newRoot: { $arrayToObject: "$array" }
}
}
])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With