16

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?

styopdev
  • 2,604
  • 4
  • 34
  • 55

3 Answers3

23

Now it's possible natively with Mongoose +4.6.1

Book.index({user: 1, author: 1, complete: 1}, {unique: true, partialFilterExpression: {complete: true}});
raphaklaus
  • 1,645
  • 1
  • 10
  • 8
  • 1
    @Alendorff there isn't. The reason I think it doesn't is because Mongoose dispatch the command to Database Engine, so Mongoose have nothing to do with. But IMHO it should. Some research will lead you to issues that use this function in Mongoose: https://github.com/Automattic/mongoose/search?q=partialFilterExpression&type=Issues&utf8=%E2%9C%93 Confirming that it is possible. – raphaklaus Aug 24 '17 at 19:24
  • can't find this in mongoose document... – MartianMartian Dec 27 '22 at 04:10
  • this actually works, i guess mongoose just passes whatever it receives to mongodb – MartianMartian Dec 27 '22 at 04:57
16

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.

TheoK
  • 3,601
  • 5
  • 27
  • 37
6

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.

everyman
  • 3,377
  • 1
  • 34
  • 33