mongodb - 如何在数组中增加 MongoDB 文档对象字段

标签 mongodb nosql

这是我的文档的格式:

{
    _id: some id,
    name: 'some name',
    versions: []
}

versions 字段中,我存储像 {v: '2.5', count: 5} 这样的对象,其中 count 保存次数一个版本正在使用中。

以下最简单的方法是什么?

  1. versions 数组中插入一个新对象(如果它不存在)
  2. 如果特定版本存在于 versions 数组中,则增加其 count

最佳答案

最简单的方式应该是,

db.collection.update({versions.v:'some_version'},{"$inc":{"versions.$.count":1}});

如果版本存在,这将增加您的计数,但正如 MongoDB 文档所说,$ 运算符不能与 upsert 混合,因此上述查询不会导致插入 if {versions. v:'some_version'} 失败。

The positional operator cannot be combined with an upsert since it requires a matching array element. If your update results in an insert then the "$" will literally be used as the field name.

以下是 JIRA 票证,用于支持 $ 的 upsert。您可以投票并观看这些问题。

Upsert with $-positional operator can create bad documents

Support $ positional operator with an upsert

关于mongodb - 如何在数组中增加 MongoDB 文档对象字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11184079/

相关文章:

database-design - Redis 集的替代品

mongodb - MongoDb 中的 nscannedObjectsAllPlans 解释是什么意思

Mongodb 查询不在带有文本字段的复合索引上使用前缀

mongodb - PyMongo:我应该使用单个客户端还是多个客户端?

haskell - 节省空间的嵌入式 Haskell 持久性解决方案

json - 完美的JSON结构

mongodb - Mongo 查询 Distinct with Sum 不起作用

node.js - 执行 mongoose 聚合查询时 _id 字段出现奇怪字符

performance - Cassandra 轻量级事务性能损失

mongodb - Mongos认证