Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Multifield Indexes in Mongoose / MongoDB

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?

like image 808
Dan Avatar asked Sep 24 '12 22:09

Dan


People also ask

Can MongoDB use multiple indexes?

MongoDB can use the intersection of multiple indexes to fulfill queries. In general, each index intersection involves two indexes; however, MongoDB can employ multiple/nested index intersections to resolve a query.

How do you create a compound index?

How to create a compound Index? In MongoDB, we can create compound index using createIndex() method. Syntax: db.

How many indexes does MongoDB create by default for a new collection?

MongoDB provides two geospatial indexes known as 2d indexes and 2d sphere indexes using these indexes we can query geospatial data.


1 Answers

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}); 
like image 81
JohnnyHK Avatar answered Oct 03 '22 14:10

JohnnyHK