Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of Index in Mongoose Schema

I am trying to add unique documents in the collection. However the problem is I want to decide uniqueness based on 2 fields. So I found a solution for it online. What confuses me is, What is the purpose ofINDEX here? In RDBMS index is usually the word used for row id, what does this mean here and how does it affect the uniqueness?

var patientSchema = mongoose.Schema({
  name : String,
  fatherOrHusbandName : String,
  address : String,
});


patientSchema .***index***({ email: 1, sweepstakes_id: 1 }, { unique: true });
like image 922
user2498079 Avatar asked Apr 24 '16 12:04

user2498079


2 Answers

Indexes support the efficient execution of queries in MongoDB. Without indexes, MongoDB must perform a collection scan, i.e. scan every document in a collection, to select those documents that match the query statement. If an appropriate index exists for a query, MongoDB can use the index to limit the number of documents it must inspect.

for more details see this documentation .

Don't be confused after reading this document because this document uses createIndex and you're code uses index. createIndex is for MongoDB and index is for mongoose that internally executes MongoDB operations.

If you have no data in your database then it will work fine

patientSchema .index({ email: 1, sweepstakes_id: 1 }, { unique: true });

but if you have some data in the database with duplicate items then you should use dropDups keyword to make it a unique index.

But one thing you should know before use dropDups. If you use dropDups: true and you have some data with duplicate value then keep one document in your database and all the other data will be deleted (duplicate data).

Like:

patientSchema .index({ email: 1, sweepstakes_id: 1 }, { unique: true, dropDups: true });
like image 130
Shaishab Roy Avatar answered Oct 19 '22 17:10

Shaishab Roy


It actually has the same purpose like indexes in RDBMS. You just have to think in some mongo-terminology. In mongodb instead of Tables, you have collections, instead of rows, you have documents. With mongoose you defined a schema for a collection 'Patient', within this collection(index belongs to Patient collection) you defined a unique index on the document properties email and sweepstakes_id.

Every time you save a document in the Patient collection, mongodb makes sure that a document which has the email and sweepstakes_id properties set, those 2 properties will be unique among all other documents.

So, instead of 'rows', think in 'documents'

like image 12
risuch Avatar answered Oct 19 '22 19:10

risuch