[英]How to update _id of all documents in a collection in mongo using node js?
[英]How do I update all documents that have an _id present in another collection with Mongo?
有 2 個集合,docIdsToUpdate 和 docs,如何從第一個集合中獲取 id 列表並更新第二個集合中的字段。
docIdsToUpdate:
_id: xxxx
docId: 1
_id: yyyy
docId: 2
文檔
_id: 1
name: "test"
deleted: false
_id: 2
name: "test 2"
deleted: false
_id: 3
name: "test 3"
deleted: false
有沒有辦法使用命令行為第一個集合中存在的 id 設置刪除:true? 最好不必在節點中運行腳本,但這是另一種選擇。
謝謝
您可以使用$merge
來執行更新。 執行$lookup
和一些爭論,然后merge
到docs
集合。
db.docs.aggregate([
{
"$lookup": {
"from": "docIdsToUpdate",
"localField": "_id",
"foreignField": "docId",
"as": "update"
}
},
{
"$unwind": "$update"
},
{
"$set": {
"deleted": true
}
},
{
"$unset": "update"
},
{
"$merge": {
"into": "docs",
"on": "_id",
"whenMatched": "replace"
}
}
])
這是Mongo 游樂場供您參考。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.