MongoDB Aggregation—在深度嵌套的对象数组中,根据其他字段的值更改字段的值



所以我的集合中有一些文档。每个对象都是一个用户对象,它包含思想,思想有回复。我想要的是,当一个回复是匿名的true,它的用户名值应该说匿名而不是用户名值。

文档

[
{
"_id": {
"$oid": "6276eb2195b181d38eee0b43"
},
"username": "abvd",
"password": "efgh",
"thoughts": [
{
"_id": {
"$oid": "62778ff975e2c8725b9276f5"
},
"text": "last  thought",
"anonymous": true,
"replies": [
{
"_id": {
"$oid": "62778fff75e2c8725b9276f5"
},
"text": "new reply",
"anonymous": true,
"username": "cdf"
},
{
"_id": {
"$oid": "62778fff75e2c8725b9276f5"
},
"text": "new reply",
"anonymous": false,
"username": "cdf"
}
]
}
]
}
]

输出要求。如果你看到username的值是anonymous尽管现有文档有"cdf"作为值

[
{
"_id": {
"$oid": "6276eb2195b181d38eee0b43"
},
"username": "abvd",
"password": "efgh",
"thoughts": [
{
"_id": {
"$oid": "62778ff975e2c8725b9276f5"
},
"text": "last  thought",
"anonymous": true,
"replies": [
{
"_id": {
"$oid": "62778fff75e2c8725b9276f5"
},
"text": "new reply",
"anonymous": true,
"username": "anonymous"
},
{
"_id": {
"$oid": "62778fff75e2c8725b9276f5"
},
"text": "new reply",
"anonymous": false,
"username": "cdf"
}
]
}
]
}
]

如果你知道如何帮助我,请告诉我。下面是包含现有文档的MongoDB Playground URL:https://mongoplayground.net/p/WoP-3z-DMuf

一个有点复杂的查询。

  1. $set-更新thoughts字段。

    1.1。$map-迭代每个thought文档并从1.1.1返回新文档。

    1.1.1。$mergeObjects-从1.1.1.1合并thoughts文档和replies数组的对象。

    1.1.1.1。$map-迭代reply文档,通过合并reply文档和username字段返回新文档,并通过$cond基于anonymous字段更新其值。

db.collection.aggregate([
{
$set: {
thoughts: {
$map: {
input: "$thoughts",
as: "thought",
in: {
$mergeObjects: [
"$$thought",
{
replies: {
$map: {
input: "$$thought.replies",
as: "reply",
in: {
$mergeObjects: [
"$$reply",
{
username: {
"$cond": {
"if": "$$reply.anonymous",
"then": "anonymous",
"else": "$$reply.username"
}
}
}
]
}
}
}
}
]
}
}
}
}
}
])

Mongo Playground示例

最新更新