Creating Multifield Indexes in Mongoose / MongoDB

MongodbMongoose

Mongodb Problem Overview


I'm trying to find documentation, to no avail, on how to create multi-field indexes in Mongoosejs. In particular I have two fields that need to be indexed and unique. What is an example mongoose schema that indexes two fields together?

Mongodb Solutions


Solution 1 - Mongodb

You call the index method on your Schema object to do that as shown here. For your case it would be something like:

mySchema.index({field1: 1, field2: 1}, {unique: true});

Solution 2 - Mongodb

Defining indexes at the schema level is necessary when creating compound indexes.

animalSchema.index({ name: 1, type: -1 });

Reference: http://mongoosejs.com/docs/guide.html#indexes

Solution 3 - Mongodb

    Following command can be used to create compound index for nested json:
    db.ACCOUNT_collection.createIndex({"account.id":1,"account.customerId":1},{unique:1}) 
Mongo json structure is like :
{"_id":"648738"
 "account": { 
    "id": "123",
    "customerId": 7879,
    "name": "test"
   ..
   ..

  }
}

I have tested with sample data it is perfectly working as expected.

Solution 4 - Mongodb

By the way, the accepted answer is wrong, as per https://stackoverflow.com/a/52553550/129300 you should wrap the field names in single quotes, ie:

mySchema.index({'field1': 1, 'field2': 1}, {unique: true});

Happy Day!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDanView Question on Stackoverflow
Solution 1 - MongodbJohnnyHKView Answer on Stackoverflow
Solution 2 - MongodbKrumbView Answer on Stackoverflow
Solution 3 - MongodbRajeev RathorView Answer on Stackoverflow
Solution 4 - MongodbFer MartinView Answer on Stackoverflow