UpdateOne and Upsert , if not exist insert another data.

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