C# 您是否必须始终知道保存在Mongodb文档数组中的索引?
如果您有这样的MongoDB阵列:C# 您是否必须始终知道保存在Mongodb文档数组中的索引?,c#,mongodb,C#,Mongodb,如果您有这样的MongoDB阵列: "array": [ { "item" : { "content": "", "extra_content": "" } }, { "item" : { "content": "", "extra_content": "" } }, { "otheritem" : { "content": "", "extra_content": "
"array": [
{
"item" : {
"content": "",
"extra_content": ""
}
},
{
"item" : {
"content": "",
"extra_content": ""
}
},
{
"otheritem" : {
"content": "",
"extra_content": ""
}
}
]
数组中的项可以具有唯一的名称,例如“otheritem”,并且有些项是重复的。我一直在通过处理数组和查找唯一项的索引来更新它,并使用Update.Set(“array.+index,bsondocument”)来更改值。是否有更好的方法更新具有唯一名称的项目?当然。使用$positional操作符:
> db.test.drop()
> db.test.insert({ "_id" : 0, "stuff" : [{ "name" : "cookie" }, { "name" : "horseshoe" }] })
> db.test.update({ "_id" : 0, "stuff.name" : "cookie" }, { "$set" : { "stuff.$.flavor" : "peanut butter" } })
> db.test.findOne()
{
"_id" : 0,
"stuff" : [
{ "name" : "cookie", "flavor" : "peanut butter" },
{ "name" : "horseshoe" }
]
}