Mongodb – How to index an property object in MongoDB

indexmongodb

I've the following sample document:

{
    "_id" : ObjectId("556e177ca43da29e040041a7"),
    "user_id" : NumberLong(24),
    "request_datetime" : ISODate("2015-06-02T15:52:12.000-05:00"),
    "total_amount" : 102.62,
    "status" : NumberLong(1),
    "adfields" : {
        "27" : "413703562015060200132",
        "28" : "S003POS4",
        "29" : "HAYLEYS",
        "30" : "1"
    }
}

The problem is that i need to index the "adfields" property, but it doesn't work with a "multikey" index type, neither using "single field index".
I tried to index the adfields property using a single field index, but when i make a query for an specific value of adfields.27 it doesn't use the index.
I can't make an single field index for adfields.27 because those numbers are created dynamically.

Do you have any idea of how to do this?
Thanks a lot.

Best Answer

I was able to make this work after altering your model. Hopefully this still fulfills the use case you are targeting. To bypass the dynamic nature of your fields, I created a field named "field" and a field named "value". This allows me to create a multikey index on known fields.

db.myColl.insert(
{

"user_id" : NumberLong(24),
"request_datetime" : ISODate("2015-06-02T15:52:12.000-05:00"),
"total_amount" : 102.62,
"status" : NumberLong(1),
"adfields" : [
    {field:"27", value : "413703562015060200132"},
    {field:"28", value: "S003POS4"},
    {field:"29", value: "HAYLEYS"},
    {field:"30", value: "1"}
    ]

})

Then I executed a find against this for db.myColl.find({"adfield.field":"30"}) for a before picture of the query. I also used db.myColl.explain().find() to analyze it.

Then I created the index via db.myColl.createIndex({"adfield.field"1,"adfield.value":1"}).

I executed the find from above and sure enough I see an IXScan and isMultiKey is true in the explain() output.

Again; hopefully the alteration to your model still keeps with the spirit of what you are attempting to accomplish.

You can read more details about mutlikey via http://docs.mongodb.org/manual/core/index-multikey/ .