1

Say I have a collection with documents like this

{
    "top_key" : [
        [
            {
                "key" : "value1"
            },
            {
                "key" : "value2"
            }
        ],
        [
            {
                "key" : "value3"
            },
            {
                "key" : "value4"
            }
        ]
    ]
}

Can I create an index for key?

Ziyuan
  • 4,215
  • 6
  • 48
  • 77
  • 1
    No. [the doc](https://docs.mongodb.com/manual/core/index-multikey/#limitations) reads: "Multikey indexes can be constructed over arrays that hold both scalar values and nested documents". Nested arrays are neither documents nor scalars. – Alex Blex Apr 21 '17 at 09:59

1 Answers1

0

Looking at this SO answer: MongoDB Query Help - query on values of any key in a sub-object

NOTE: This answer contains suggestion to update the schema in order to achieve desired result. Change the schema from:

{
    "top_key" : [
        [
            {
                "key" : "value1"
            },
            {
                "key" : "value2"
            }
        ],
        [
            {
                "key" : "value3"
            },
            {
                "key" : "value4"
            }
        ]
    ]
}

to something like this:

{
    "top_key" : [
        {
            key_name: "key", key_value: "value1"
        },
        {
            key_name: "key", key_value: "value2"
        },
        {
            key_name: "key", key_value: "value3"
        },
        {
            key_name: "key", key_value: "value4"
        }
    ]
}

Then you can index on top_key.key_value and query in a way:

db.settings.ensureIndex({ "top_key.key_value" : 1})

db.settings.find({ "top_key.key_value" : "value4" })

Do let me know if it helps.

Nishutosh Sharma
  • 1,926
  • 2
  • 24
  • 39