所以我的集合中有一些文档。每个对象都是一个用户对象,它包含思想,思想有回复。我想要的是,当一个回复是匿名的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
一个有点复杂的查询。
-
$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示例