In MongoDB, I can do it by two operations(findOne+insertOne).
Note that upsert is not acceptable because I don’t want to modify the existing item.
This is a critical and frequent operation that I wish to optimize. Is that possible?
Put in another way, when undertone, it would be nice to return the duplicate item in the write error
you can do it using findOneAndUpdate, something like this
<code>findOneAndUpdate(
{ _id: newUser._id },
{ $setOnInsert: newUser },
{ upsert: true, returnNewDocument: true }
);
</code>
<code>findOneAndUpdate(
{ _id: newUser._id },
{ $setOnInsert: newUser },
{ upsert: true, returnNewDocument: true }
);
</code>
findOneAndUpdate(
{ _id: newUser._id },
{ $setOnInsert: newUser },
{ upsert: true, returnNewDocument: true }
);
New contributor
ishaan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1