![](/img/trans.png)
[英]How to get the index of an array element in older versions on Mongodb?
[英]How to pass the index of an array element parametrically in MongoDB?
我收集了類似於以下內容的文件:
{
_id: ObjectId("..."),
title: "...",
body: "...",
comments: [
{
name: "...",
email: "...",
comment: "..."
},
{
name: "...",
email: "...",
comment: "..."
},
{
name: "...",
email: "...",
comment: "..."
}
]
}
假設我要更新第二條評論的名稱字段。 因此,我將有如下查詢:
db.posts.update({_id: ""}, {$set: {"comments.2.name": "new name"}});
現在,我想知道如何將數組元素(2)的索引作為參數/變量傳遞給node.js?
答案是簡單地用代碼構造對象。 對象鍵使用JavaScript和支持該符號的大多數其他語言進行字符串化,因此只需在外部構建字符串並使用對象符號方法即可:
var index = 1, // n-1 for array index notation of the second element
name = "new name";
var update = { "$set": { } },
query = {};
update["$set"]["comments." + index + ".name"] = name;
// Then update as normal
db.posts.udate(query,update);
使用正確的“點符號”格式構建對象
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.