2

I would like to get a list of items from an external resource periodically and save them into a collection.

There are several possible solutions but they are not optimal, for example:

  1. Delete the entire collection and save the new list of items

  2. Get all items from the collection using "find({})" and use it to filter out existing items and save those that do not exist.

But a better solution will be to set a unique key and just do kind of "update or insert". Right now on saving items the unique key already exists I will get an error is there a way to do it at all?

**upsert won't do the work since it's updating all items with the same value so it's actually good for a single document only

2
  • 1
    Welcome to SO. To help others to answer your question, please provide some sample data and code of you have tried so far. Commented Oct 15, 2018 at 17:26
  • Possible duplicate of Insert or update many documents in MongoDB Commented Oct 15, 2018 at 19:56

1 Answer 1

0

I have a feeling you can achieve what you want simply by using the "normal" insertMany with the ordered option set to false. The documentation states that

Note that one document was inserted: The first document of _id: 13 will insert successfully, but the second insert will fail. This will also stop additional documents left in the queue from being inserted. With ordered to false, the insert operation would continue with any remaining documents.

So you will get "duplicate key" exceptions which, however, you can simply ignore in your case.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.