Question

MongoDB's docs explain multi-key indexing. Consider this comment document.

{
 "_id": ObjectId(...)
 "title": "Grocery Quality"
 "comments": [
    { author_id: ObjectId(...)
      date: Date(...)
      text: "Please expand the cheddar selection." },
    { author_id: ObjectId(...)
      date: Date(...)
      text: "Please expand the mustard selection." },
    { author_id: ObjectId(...)
      date: Date(...)
      text: "Please expand the olive selection." }
 ]
}

The docs explain that it's possible to index on the comments.text, or any comments' field. However, is it possible to index on the comments key itself?

This post demonstrates indexing on an array of strings, however, the above comments field is an array of JSON objects.

Based on Antoine Girbal's article, it appears possible to index on an array of JSON objects where each JSON object has a different key name. However, it doesn't appear possible where each JSON object in the array shares the same key names.

Example - https://gist.github.com/kman007us/6797422

Was it helpful?

Solution

Yes you can index subdocuments and they can be in a multikey index. When indexing a whole subdocuments, it will only match when searching against the whole document eg:

db.test.find({records: {hair: "brown"}})

Searches for records that match documents that are exactly {hair: "brown"} and it can use the index to find it.

If you want to find any sub documents that have hair="brown" and any other fields the dot notation is needed eg:

db.test.find({"records.hair": "brown"})

However, there is no index to use for that - so its a full table scan.

Please note: There are limitations on index size and whole documents could easily exceed that size.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top