mongodbmongodb-querycompound-index

How to create a compound index for speicifc documents in mongodb


I'm running MongoDB 4.2, see below how my documents look like:

{
    "_id" : ObjectId("61e8e5b72e74b7fc3e16b632"),
    "1" : 2,
    "age_upon_outcome" : "1 year",
    "animal_id" : "A725717",
    "animal_type" : "Cat",
    "breed" : "Domestic Shorthair Mix",
    "color" : "Silver Tabby",
    "date_of_birth" : "2015-05-02",
    "datetime" : "2016-05-06 10:49:00",
    "monthyear" : "2016-05-06T10:49:00",
    "name" : "",
    "outcome_subtype" : "SCRP",
    "outcome_type" : "Transfer",
    "sex_upon_outcome" : "Spayed Female",
    "location_lat" : 30.6525984560228,
    "location_long" : -97.7419963476444,
    "age_upon_outcome_in_weeks" : 52.9215277777778
}

Bottom line is that I need to create a compound index that will improve the performance of queries looking for breeds that have an “outcome_type” of “Transfer”, and I'm not sure of how to narrow down the command below to only documents with outcome_type=Transfer

db.collection.createIndex( { breed: 1 } )

Solution

  • Would be this one:

    db.collection.createIndex(
       { breed: 1 },
       { partialFilterExpression: { outcome_type: 'Transfer' } }
    )