I'm trying to make a query by merging from another collection, but there are obstacles when the query is run, the data generated is not what I imagined
i have the data like this
{
"_id": "5ce8981a46039c14a4ec32d1",
"name": "Monkey D Luffy",
"email": "[email protected]",
"status": "not verified",
"password": "$2a$10$ayluBIsOOelBTIk.69GjHubgQemr6dJfgBUELNusCOaUGLpS/qKs6",
"metas": {
"role": "admin",
"smartphone": "ios",
"address": "konoha",
"hobby": "eat ramen"
}
},
and i want pull out metas from nested document :
{
"_id": "5ce8981a46039c14a4ec32d1",
"name": "Monkey D Luffy",
"email": "[email protected]",
"status": "not verified",
"password": "$2a$10$ayluBIsOOelBTIk.69GjHubgQemr6dJfgBUELNusCOaUGLpS/qKs6",
"role": "admin",
"smartphone": "ios",
"address": "konoha",
"hobby": "eat ramen"
},
if any duplicate from my question pls suggest me, because I didn't find the same question, mostly using arrays.
and here is my query:
db.accounts.aggregate([
{
$lookup: {
from: "account_meta",
localField: "_id",
foreignField: "account_id",
as: "metas"
}
},
{ "$unwind": "$metas" },
{
$group: {
_id: "$_id",
name: {$first:"$name"},
status: {$first: "$status"},
email: {$first: "$email"},
password: {$first: "$password"},
data: {
"$push": {
"k" : "$metas.key",
"v": "$metas.value"
}
}
}
},
{
$project: {
"_id": "$_id",
"name": "$name",
"email": "$email",
"status": "$status",
"password": "$password",
"metas" :{
$arrayToObject: "$data"
}
}
},
{
"$replaceRoot": {
"newRoot":
{
"$mergeObjects": [ {$arrayToObject: "$data"}, "$$ROOT"]
},
}
},
])
i just edit some code from my $mergeObject:
{
"$replaceRoot": {
"newRoot":
{
"$mergeObjects": [ "$metas", "$$ROOT"]
},
}
},
{$project: { metas: 0} }
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