UpdateOne and Upsert , if not exist insert another data.

Can i do this one transaction ? :thinking:

  1. UpdateOne(conditon)
  2. Insert Data Object $set
  3. if condition not met, upsert:true
  4. if data exist, $push in the the existing data, but only in the array, do not upsert the whole document.

Currently i have this
db().collection(‘Users’).updateOne({ email: data.email },
{ $set: insertData },
{ upsert: true })

that works well if the data does not exisit, but if it does exist, then i need to $push : {item : arrayItem }
instead of $set insertData

Hi @Rishi_uttam,

Welcome to MongoDB community!

What you probably looking for can be achieved with separating the insert logic to $setOnInsert operator:
https://docs.mongodb.com/manual/reference/operator/update/setOnInsert/

This allows you to do $push or $addToSet clause for updates and a different logic for $setOnInsert.

Example:

db().collection(‘Users’).updateOne({ email: data.email },
{ $push: { item : arrayItem },
$setOnInsert : { insertData} },
{ upsert: true })

Thanks
Pavel

2 Likes