简体   繁体   中英

How to increment MongoDB document object fields inside an array

This is the format of my document:

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

In the versions field I store objects like {v: '2.5', count: 5} where count holds the number of times a version is in used.

What is the simplest way to do the following?

  1. Insert a new object inside the versions array if it doesn't exist
  2. Ff a particular version exists inside the versions array then increment its count

Simplest way being should be,

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

This will increment your count if version is exist, but as MongoDB documentation says, $ operator cannot be mixed with upsert, so above query won't result in insert if {versions.v:'some_version'} fails.

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.

Below are JIRA tickets for supporting upsert with $. You can vote and watch these issue.

Upsert with $-positional operator can create bad documents

Support $ positional operator with an upsert

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM