Search code examples
mongodbmongodb-querymongodb-indexes

Mongodb partial index on one of the indexed field


I want to create partial index on one of the indexed field but I am failing miserably

db.Comment.createIndex(
 { "siteId": 1,
 { { "parent": 1} ,{partialFilterExpression:{parent:{$exists: true}}}},
 "updatedDate": 1,
 "label": 1 } 
);

how to do that?

the field "parent" is the one I want to index partially

In roboMongo I get the error Error: Line 3: Unexpected token {


Solution

  • You pass the partialFilterExpression object as a second parameter to createIndex. See the documentation.

    db.Comment.createIndex(
      { "siteId": 1, "parent": 1, "updatedDate": 1, "label": 1 },
      { partialFilterExpression: { parent: { $exists: true } }
    );
    

    So don't think of it as partially indexing a field; your partial filter expression defines which documents to include in your index.