logo image

How to create MongoDB index?


How to create MongoDB indexes on single field and multiple fields?

1 Answer

1 year ago by

1. Creating on one field

You can use the following syntax to create index on one field

db.collection.createIndex(field, options);

Ex.

db.users.createIndex( {name : 1}, {} );

1. Creating on multiple fields

You can use the following syntax to create index on multiple fields

db.collection.createIndex(fields, options);

Ex.

db.users.createIndex( {name : 1, age:  1}, {});
1 year ago by Megamind