Create index on multiple fields(compound index) in collection in MongoDB

You are here : Home / MongoDB Tutorial


Contents of page >
  • 1) Indexing in collection (table) in mongoDB >
  • 2) Create index on multiple fields(compound index) in collection in MongoDB


1) Indexing in collection (table) in mongoDB >


Let's create collection and insert records in it before indexing>
> db.employee.insert({empId : 1,  firstName:"ankit"})
> db.employee.insert({empId : 2,  firstName:"sam"})
First line above will create table (or collection) (if collection already exists it will insert records in it).


1.6) Now, let’s create index on field empId >
> db.employee.ensureIndex({empId : 1})
Now, index have been created on field empId.
Here 1 is to create index in ascending order.
You can also use -1 is to create index in descending order.


2) Create index on multiple fields(compound index) in collection in MongoDB >
> db.employee.ensureIndex({empId : 1}, {firstName : 1})


Now, index have been created on field empId and firstName.


Having any doubt? or you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter. You may join our fbGroup or linkedInGroup as well.


RELATED LINKS>

What is MongoDB - A quick introduction to database


eEdit
Must read for you :