简体   繁体   中英

MongoDB: Insert a document if not exist, but skip updating in case it already exists

How do I insert a document in mongoose if not exist without doing an update on the existing one if it already exists? I know if I do an upsert it tries to update if exist and inserts a new document if it doesn't exist. However, my situation is that I just want to insert a new document if not exist and leave the existing one without updating it.

You are on the right way. You should use still use upsert in the update method but also with the $setOnInsert operator. Please, read about this operator here .

In short words, using this operator allows you to perform operation only if it results in inserting new document. In other case it will simply skip.

And yes, you of course can use this with mongoose:

YourModel.update(
  { queryField: 1 }, // query
  { $setOnInsert: { ...newDocument }}, // new doc fields
  { upsert: true } // still use upsert option
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM