0

I have worked a lot with sql like databases but when it comes to nosql dbs my knowledge is limited. Planning the design of my application I asked myself if there are differences when you want to find an entry in the database and the parameters used for identification.

For example: To avoid duplicates I want to check the database if the entry exists before using the insertOne command. Are there any differences whether I use the _id field or an attribute I defined myself in the query when it comes to efficiency and speed? I think that the collection will not hold more than 10.000 items.

Because I’m able to set the _id field when inserting a dataset manually this could impact the overall performance.

1
  • 1
    Mongodb is not any different from relational databases in this regard. If a field is indexed, searches/lookups by that field will be fast. Commented Nov 16, 2019 at 15:21

1 Answer 1

1

Like with SQL databases, you can add indexes on arbitrary fields in MongoDB. There should not be a noticable difference between reads based on the _id index or on your own.

To avoid duplicates I want to check the database if the entry exists before using the insertOne command.

You should have a look at the upsert parameter which handles exactly this usecase. It either updates or inserts a document (hence the name, up-sert). Refer the MongoDB Node.js driver documentation for details.

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

2 Comments

Are there any differences when I dont use another index? Therefore I may have two options: a) Overwrite the _id with the value of the attribute I would use to compare otherwise or b) create an index on that attribute
Without an index, the DB must perform a collection scan (i.e. it looks through every single collection). So yes, there is certainly a difference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.