这是我的文档的格式:
{
_id: some id,
name: 'some name',
versions: []
}
在 versions
字段中,我存储像 {v: '2.5', count: 5}
这样的对象,其中 count
保存次数一个版本正在使用中。
以下最简单的方法是什么?
- 在
versions
数组中插入一个新对象(如果它不存在) - 如果特定版本存在于
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。您可以投票并观看这些问题。
关于mongodb - 如何在数组中增加 MongoDB 文档对象字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11184079/