Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial indexes in mongodb / mongoose

In the sparse index documentation I found note about mongodb 3.2 partial indexes

Changed in version 3.2: Starting in MongoDB 3.2, MongoDB provides the option to create partial indexes. Partial indexes offer a superset of the functionality of sparse indexes. If you are using MongoDB 3.2 or later, partial indexes should be preferred over sparse indexes.

Partial indexes are very helpfull and I want to use them in my project. Is it possible use them with mongoose?

like image 494
styopdev Avatar asked Jan 27 '16 07:01

styopdev


People also ask

What are partial indexes in MongoDB?

Partial indexes only index the documents in a collection that meet a specified filter expression. By indexing a subset of the documents in a collection, partial indexes have lower storage requirements and reduced performance costs for index creation and maintenance.

How do partial indexes work?

A partial index is an index built over a subset of a table; the subset is defined by a conditional expression (called the predicate of the partial index). The index contains entries only for those table rows that satisfy the predicate.

Can MongoDB use part of a compound index?

MongoDB can use the intersection of indexes to fulfill queries. For queries that specify compound query conditions, if one index can fulfill a part of a query condition, and another index can fulfill another part of the query condition, then MongoDB can use the intersection of the two indexes to fulfill the query.

What is schema index in mongoose?

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 .


3 Answers

Now it's possible natively with Mongoose +4.6.1

Book.index({user: 1, author: 1, complete: 1}, {unique: true, partialFilterExpression: {complete: true}});
like image 111
raphaklaus Avatar answered Oct 09 '22 17:10

raphaklaus


In the current Mongoose version 4.3.7 you cannot define partial indexes in the scheme, but you can still use Partial Indexes of MongoDB 3.2.

You just have to create the indexes using the native driver.

// ScheduleModel is a Mongoose Model
ScheduleModel.collection.createIndex({"type" : 1 } , {background:true , partialFilterExpression : { type :"g" }} , function(err , result){
     console.log(err , result);
});

After that, every query that matches the partialFilterExpression will be indexed.

like image 26
Angelos Veglektsis Avatar answered Oct 09 '22 15:10

Angelos Veglektsis


For Mongoid users:

index(
  { user_id: 1, author_id: 1, complete: 1 },
  background: true,
  partial_filter_expression:
    {
      complete: { :$eq => true }
    }
)

Couldn't find any docs, but this PR.

like image 6
everyman Avatar answered Oct 09 '22 17:10

everyman