MongoDB 将对象元素合并到聚合中的另一个元素
MongoDB merging an object element to another element from aggregate
所以我现在有这个对象
{
"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"
}
]
}
如何将 username, status, createdAt, id
合并到 author
元素。所以结果是
{
"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"
}
]
}
这是我现在正在使用的代码,我使用查找来获取其他作者对象,例如用户名或 ID
- 抱歉,我把它放在 sourcebin 中,因为它很长而且我不想让表格变得凌乱
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"
}
}
}
}
}
])
所以我现在有这个对象
{
"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"
}
]
}
如何将 username, status, createdAt, id
合并到 author
元素。所以结果是
{
"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"
}
]
}
这是我现在正在使用的代码,我使用查找来获取其他作者对象,例如用户名或 ID
- 抱歉,我把它放在 sourcebin 中,因为它很长而且我不想让表格变得凌乱
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"
}
}
}
}
}
])