Mongodb update conditional set operator ($set only when it is insert )

493 views
Skip to first unread message

Virendra Agarwal

unread,
Mar 10, 2015, 3:33:09 AM3/10/15
to mongod...@googlegroups.com
HI,

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



Virendra Agarwal

unread,
Mar 10, 2015, 4:42:59 AM3/10/15
to mongod...@googlegroups.com

Virendra Agarwal

unread,
Mar 12, 2015, 1:51:33 AM3/12/15
to mongod...@googlegroups.com
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.

Reply all
Reply to author
Forward
0 new messages