mongodb - 如何增加 MongoDB 中索引引用的数组元素?

标签 mongodb

假设我们有一个包含如下文档的集合:

{
 _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/

相关文章:

node.js - 如何在mongodb的子字段(数组)中进行聚合和分组?

android - Heroku + mongolab 沙箱应用程序部署在 Play 商店中

mongodb - mongo shell 可以警告对不存在的集合的操作吗?

MongoDB 文本索引错误 : language override not supported

javascript - 从 PHP7 调用 Mongodb 存储函数

node.js - 来自其他集合的 Mongoose 文档群体

javascript - 为什么参数 multi 在 mongo 请求中不起作用?

mongodb - MongoDB 中的命令和方法有什么区别?

mongodb - 蒙戈错误: Incorrect arguments

mongodb - wolvenkit:数据库访问和备份