How to increase fields of a MongoDB document object inside an array

This is the format of my document:

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

Objects of type {v: '2.5', count: 5} are stored in the versions field, where count contains the number of times the version is used.

What is the easiest way to do the following?

  • Insert a new object inside the versions array if it does not exist
  • Ff a specific version exists inside the versions array, then increment its count
+7
source share
1 answer

The simplest way should be

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

This will increase your counter if a version exists, but as MongoDB says, the $ operator cannot be mixed with upsert, so the above request will not result in an insertion if {versions.v:'some_version'} does not work.

A positional operator cannot be combined with a raise because it requires the corresponding array element. If your update results in an insert, then the letter "$" will be used as the field name.

Below are JIRA tickets for upsert support with $. You can vote and see this problem.

Acceleration with the $ -position operator can create bad documents

Support $ positional operator with upsert

+10
source

All Articles