我試圖在檔案的評論陣列中切換喜歡評論的人的姓名。
比文字更直觀:Mongo Playground Link
說明:
假設我有一個檔案
{
"id": 1,
"comments": [
{
"id": 1,
"text": "Comment 1",
"likedBy": [
"Tomato",
"Potato"
],
},
{
"id": 2,
"text": "Comment 2",
"likedBy": [
"Carrot"
],
},
],
},
我想在檔案中likedBy匹配的特定評論上“切換”一個值“Potato” comments.id。
到目前為止,我想出了這個
db.collection.update({
id: 1,
"comments.id": 1,
},
[
{
$set: {
"comments.likedBy": {
$cond: [
{
$in: [
"Potato",
"$comments.likedBy"
]
},
{
$setDifference: [
"$comments.likedBy",
[
"Potato"
]
]
},
{
$concatArrays: [
"$comments.likedBy",
[
"Potato"
]
]
}
],
},
},
}
])
預期輸出:
{
"id": 1,
"comments": [
{
"id": 1,
"likedBy": [
"Tomato",
//!! Potato is removed from here
],
"text": "Comment 1"
},
{
"id": 2,
"likedBy": [
"Carrot"
],
"text": "Comment 2"
}
],
}
但是,我得到的結果不正確。我有一種感覺,我在使用位置運算子時做錯了。
uj5u.com熱心網友回復:
詢問
- 如果它存在,這將洗掉
"Potato"fromlikeBy否則添加"Potato" $map在評論上,如果comment.id=1添加/洗掉"Potato"其他評論,請保持原樣- 在下面的代碼中
$$this是評論子檔案
*不確定這是否正是您所需要的,但會產生您想要的結果,并且看起來像您的查詢。
*關于路徑,“$comments.likedBy”是一個包含likedBy來自所有評論的所有陣列的陣列,$map波紋管$$this.likedBy僅用于包含特定評論的likedBy,我認為這是問題所在。
測驗代碼在這里
update(
{"id": 1,"comments.id": 1},
[{"$set":
{"comments":
{"$map":
{"input": "$comments",
"in":
{"$cond":
[{"$eq": ["$$this.id", 1]},
{"$mergeObjects":
["$$this",
{"likedBy":
{"$cond":
[{"$in": ["Potato", "$$this.likedBy"]},
{"$setDifference": ["$$this.likedBy", ["Potato"]]},
{"$concatArrays": ["$$this.likedBy", ["Potato"]]}]}}]},
"$$this"]}}}}}])
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/371145.html
標籤:MongoDB 猫鼬 mongodb-查询
