Can i do this one transaction ?
- UpdateOne(conditon)
- Insert Data Object $set
- if condition not met, upsert:true
- 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
1 Like
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