在单个数组字段上创建复合索引

时间:2013-07-15 15:33:34

标签: mongodb indexing

我想在一个包含数组的字段上创建索引。默认情况下,当在这样的字段上创建索引时,mongo会分别索引每个数组中的每个项目。

但是,我希望索引是一个复合索引,类似于子文档字段上的索引(我希望索引是唯一的,['a', 'b']['b', 'a']不同)。在monogo有没有办法做到这一点?

2 个答案:

答案 0 :(得分:0)

您可以通过按如下方式存储数据来执行此操作:

{ 
    field: { v: [ a, "b" ] }
}

然后做一个索引:

db.collection.ensureIndex( { field: 1 } );

我知道这有点反直觉,但“字段”的索引现在将用作索引值:

v: [ a, "b" ]

而不是每个a和“b”单独。当然你可以使用其他东西作为“v”,但重要的是字段的值是文档,而不是数组。

查询:

db.collection.find( { field: { v: [ 'a', 'b' ] } } )

然后会愉快地使用索引:

{
    "cursor" : "BtreeCursor field_1",
    "isMultiKey" : false,
    "n" : 1,
    "nscannedObjects" : 1,
    "nscanned" : 1,
    "nscannedObjectsAllPlans" : 1,
    "nscannedAllPlans" : 1,
    "scanAndOrder" : false,
    "indexOnly" : false,
    "nYields" : 0,
    "nChunkSkips" : 0,
    "millis" : 0,
    "indexBounds" : {
        "field" : [
            [
                {
                    "v" : [ "a", "b" ]
                },
                {
                    "v" : [ "a", "b" ]
                }
            ]
        ]
    },
    "server" : "whisky:27017"
}

答案 1 :(得分:-1)

对于在包装字段上进行索引时是否使用索引的问题,是的,它确实使用索引。 shell中的以下陈述证明了这一点。

> db.arrayindtest.insert({_id:1, f:{a:["a","b"]}})
> db.arrayindtest.insert({_id:2, f:{a:["b","a"]}})
> db.arrayindtest.insert({_id:3, f:{a:["a","b", "c"]}})
> db.arrayindtest.ensureIndex({f:1})
> db.arrayindtest.find({f:{a:["a","b"]}})
{ "_id" : 1, "f" : { "a" : [  "a",  "b" ] } }
> db.arrayindtest.find({f:{a:["a","b"]}}).explain()
{
        "cursor" : "BtreeCursor f_1",
        "isMultiKey" : false,
        "n" : 1,
        "nscannedObjects" : 1,
        "nscanned" : 1,
        "nscannedObjectsAllPlans" : 1,
        "nscannedAllPlans" : 1,
        "scanAndOrder" : false,
        "indexOnly" : false,
        "nYields" : 0,
        "nChunkSkips" : 0,
        "millis" : 0,
        "indexBounds" : {
                "f" : [
                        [
                                {
                                        "a" : [
                                                "a",
                                                "b"
                                        ]
                                },
                                {
                                        "a" : [
                                                "a",
                                                "b"
                                        ]
                                }
                        ]
                ]
        },
        "server" : "sridhar-PC:27017"
}
>
相关问题