假设我们有一个包含如下文档的集合:
{
_id : "some id",
items: [
{item: "item A", count: 5},
{item: "item B", count: 3},
{item: "item C", count: 9}
]
}
如何将 items 数组中的第三个(或任何其他索引值)元素的值增加 1?
我不想通过匹配 question 中的值来引用,但按索引。
最佳答案
在 mongo shell 中可以这样做:
db.my_collection.update(
{_id: "some id"},
{$inc: {"items.2.count": 1}}
)
使用 PyMongo 可以这样做:
db.my_collection.update_one({"_id": "some id"},
{"$inc": {"items." + str(2) + ".count": 1}})
关于mongodb - 如何增加 MongoDB 中索引引用的数组元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34179117/