'MongoDB merging an object element to another element from aggregate [closed]
So currently I have this object right now
{
"notifications": [
{
"author": "5862184743205863247",
"type": "friend",
"value": "5862184743205863247",
"avatar": "https://avatars.dicebear.com/api/avataaars/ZAZA.png",
"id": "5861675623319076687",
"createdAt": "2022-03-24T13:43:06.637Z",
"status": "Hello! I just joined unchat!",
"username": "ZAZA"
}
]
}
How do I merge the username, status, createdAt, id to the author element. So the result would be
{
"notifications": [
{
"author": {
"avatar": "https://avatars.dicebear.com/api/avataaars/ZAZA.png",
"id": "5861675623319076687",
"createdAt": "2022-03-24T13:43:06.637Z",
"status": "Hello! I just joined unchat!",
"username": "ZAZA"
},
"type": "friend",
"value": "5862184743205863247"
}
]
}
This is the code I am using right now, I used a lookup to get the other author objects like the username or the id
- Sorry I put it in sourcebin because it was long and I didn't wnat the form to be messy
Solution 1:[1]
db.collection.aggregate([
{
$set: {
notifications: {
$map: {
input: "$notifications",
as: "n",
in: {
author: {
avatar: "$$n.avatar",
id: "$$n.id",
createdAt: "$$n.createdAt",
status: "$$n.status",
username: "$$n.username"
},
type: "$$n.type",
value: "$$n.value"
}
}
}
}
}
])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
