【问题标题】:How can I increment an array element referenced by index in MongoDB?如何增加 MongoDB 中索引引用的数组元素?
【发布时间】:2016-03-14 17:51:45
【问题描述】:

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

{
 _id : "some id",
 items: [
  {item: "item A", count: 5},
  {item: "item B", count: 3},
  {item: "item C", count: 9}
]
}

如何将 items 数组中的第三个(或任何其他索引值)元素的值增加 1?

我不想像 question 那样通过匹配值来引用,而是通过索引来引用。

【问题讨论】:

  • 既然已经知道答案,为什么还要问这个问题?也可能重复stackoverflow.com/questions/16037788/…
  • @SarathNair 完全没问题。尽管它是重复的。 meta.stackoverflow.com/questions/290038/…
  • @Idos “所以我想出了一个问题,做了我的研究,并没有发现对 S.O 的帮助”这个问题已经在 SO 中得到了解答
  • 我已经看到提到的问题,我认为有足够的差异可以单独添加。在我的例子中,它是由索引引用的,而不是匹配值。

标签: mongodb


【解决方案1】:

在 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}}) 

【讨论】:

  • 如果数组实际上不存在怎么办?它不是创建[1],而是创建{"0": 1}。我如何要求它在那里使用整数键?
猜你喜欢
  • 2012-07-07
  • 2013-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-26
  • 2011-10-08
  • 2019-12-12
相关资源
最近更新 更多