我的文档结构如下。
{
_id: ...,
unique_id: 1234,
config_no: 1,
configs: [
{
data: "qwertyuiop" // random string
},
{
data: "asdfghjkl" // random string
}
]
}
我想从其中一个configs
更新data
的值。需要更新的config
的索引在config_no
键中可用。
是否有任何方法可以在不查询文档的情况下更新该值。
这是我目前正在做的事情
doc = db.collection.findOne({"unique_id": 1234})
config_no = doc.config_no
db.collection.updateOne(
{"unique_id": 1234},
{"$set": {"configs."+config_no+".data": "zxcvbnm"}} //"configs.1.data"
)
以下是我想达到的目标。
db.collection.updateOne(
{"unique_id": 1234},
{"$set": {"configs.${config_no}.data": "zxcvbnm"}}
)
1条答案
按热度按时间0g0grzrc1#
可以使用
includeArrayIndex
选项$unwind
.使用索引执行条件更新并将$merge
放回集合中。Mongo Playground