2

Is it possible to create a mongodb index on subdocuments keys which can be different in each document? For instance if we have

{ 
    _id: 1, 
    languages: {
        en: {...},
        fr: {...},
        de: {...}
    }
},
{ 
    _id: 2, 
    languages: {
        cs: {...},
        fr: {...}
    }
}

... to create and index on the languages' keys so later in the find() just to check if this language exists(something like "languages.fr": {$exists: true}).

I suppose this should be similar to creating an index on array field if the languages were an array:

{ _id: 1, languages: ['en', 'fr', 'de']},
{ _id: 2, languages: ['cs', 'fr']}


db.coll.createIndex( { languages: 1 } )
mtonev
  • 327
  • 3
  • 7

1 Answers1

2

Is it possible to create a mongodb index on subdocuments keys which can be different in each document?

Nope. Instead, you'll want to use a faceted search data model that allows you to create a generic index.

For example:

{
 _id : 1, 
 languages: [
   { "language": "en", "content" : ... },
   { "language": "fr", "content" : ... },
   { "language": "de", "content" : ... },
   ...
 ]
}

Queries could then look something like the following:

db.coll.find({ 
  "languages" : { 
    "$elemMatch" : { 
      "language" : "en", "content" : ... 
    }
  }
})

or

db.coll.find(( { "languages.language" : "en" } )

(see link above for detailed explanation)

The index on the collection would be:

{ "languages.language" : 1, "languages.content" : 1 }
Adam Harrison
  • 3,323
  • 2
  • 17
  • 25
  • 3
    *"Yes, if your data model can support it."* - Should that not be *"No, you cannot. Do this instead...."* Because that is what you are actually saying here. You cannot index a "key" ( as the question presents and asks ) and you should in fact be "using an array". So you're presenting the right structure of the solution but sending the wrong message by saying YES. I agree with the structure, but the message is just causing confusion. – Neil Lunn May 17 '18 at 00:22