Dmitry Zhlobo
Dmitry Zhlobo

Reputation: 379

MongoDB multikey indexes for array of attributes

I have 3 documents in my products collection:

samsung = {
  title: 'Samsung Galaxy S III',
  category_id: ObjectId("50bcc2f0b910a6c1936a4424"),
  properties: [
    {
      title: 'OS',
      value: 'Android'
    },
    {
      title: 'Display',
      value: '4.8"'
    }
  ]
}

htc = {
  title: 'HTC One X',
  category_id: ObjectId("50bcc2f0b910a6c1936a4424"),
  properties: [
    {
      title: 'OS',
      value: 'Android'
    },
    {
      title: 'Display',
      value: '4.7"'
    }
  ]
}

apple = {
  title: 'Apple iPhone 5',
  category_id: ObjectId("50bcc2f0b910a6c1936a4424"),
  properties: [
    {
      title: 'OS',
      value: 'iOS'
    },
    {
      title: 'Display',
      value: '4"'
    }
  ]
}

and index {category_id: 1, 'properties.title': 1, 'properties.value': 1}.

I think index should looks like:

ObjectId("50bcc2f0b910a6c1936a4424")
  OS
    Android
      samsung
      htc
    iOS
      apple
  Display
    4.8"
      samsung
    4.7"
      htc
    4"
      apple

And I expect for that query:

{
  category_id: ObjectId("50bcc2f0b910a6c1936a4424"),
  properties: {
    $elemMatch: {
      title: 'OS',
      value: 'Android'
    }
  }
}

nscanned == 2, nscannedObjects == 2, n == 2. But I get such output by explain():

{
        "cursor" : "BtreeCursor category_id_1_properties.title_1_properties.value_1",
        "nscanned" : 3,
        "nscannedObjects" : 3,
        "n" : 2,
        "millis" : 0,
        "nYields" : 0,
        "nChunkSkips" : 0,
        "isMultiKey" : true,
        "indexOnly" : false,
        "indexBounds" : {
                "category_id" : [
                        [
                                ObjectId("50bcc2f0b910a6c1936a4424"),
                                ObjectId("50bcc2f0b910a6c1936a4424")
                        ]
                ],
                "properties.title" : [
                        [
                                "OS",
                                "OS"
                        ]
                ],
                "properties.value" : [
                        [
                                {
                                        "$minElement" : 1
                                },
                                {
                                        "$maxElement" : 1
                                }
                        ]
                ]
        }
}

Can you please explain me why indexBounds for "properties.value" isn't ["Android","Android"]?

Can I rewrite query or rebuild my index for getting right phones using index?

Upvotes: 0

Views: 332

Answers (1)

Dmitry Zhlobo
Dmitry Zhlobo

Reputation: 379

It's a bug of MongoDB: https://jira.mongodb.org/browse/SERVER-3104.

Development version 2.3.1 have the same bug, but in the latest nightly build (I've tested on 2012-12-03) everything seems to work fine.

Upvotes: 1

Related Questions