4

Is there anything in Mongo update where $set when will work only when an insert is done.

example is I have a collection which has these fields:

  1. Username
  2. FirstOccurrence
  3. Count

What i want that i will run a update operation like this.

coll.update{ q: {username} ,u: {$set:{FirstOccurrence},$inc:count} }

But condition will be if UserName is already existing then it wont run the $set it will just increment the count.

Is it possible to do it I am running Mongo 2.6.4 with Java driver 2.13.0

Regards Viren

1 Answer 1

5

It will work for conditional $set update operation

http://docs.mongodb.org/manual/reference/operator/update/setOnInsert/

db.products.update(
  { _id: 1 },
  {
    $set: { item: "apple" },
    $setOnInsert: { defaultQty: 100 }
  },
  {upsert: true }
)

Here setOnInsert will set defaultQty only when a new record is inserted. Both $set and $setOnInsert can be used together.

3
  • 3
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. Commented Mar 10, 2015 at 14:48
  • 3
    @Colin'tHart have added an example to it. Thanks for pointing this out.
    – viren
    Commented Mar 11, 2015 at 3:03
  • You have not answered the question. The questions asked about $inc which you missed Commented Jan 27, 2020 at 12:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.