0

if i have in mongodb a array structure like this:

"field":
[
     [10,20]  //specified length per array
     [25,40]
     [60,90]
     ...and so on, with various size per document
]

how can i index this subarrays? i tried to index with: db.ensureIndex({"field.$.0":1}); //and {"field.$.1":1}

but searching in documents is remained slow.

I tried also this solution: MongoDB, array of arrays index but

db.ensureIndex("{field:[{"a":1}]}"); //and "{field:[{"b":1}]}" 

if a naming the subarray indexes a and b, this sintax throws "bad index key pattern" exception.

4

1 回答 1

3

你能解释更多你想要做什么吗?第一个架构设计不是很好;您有一堆数组,除了使用可能非常慢的数组运算符之外,您真的无法解决。

看来您的第二个想法已经步入正轨,但是您的语法有点偏离。如果您可以插入文档而不是子数组,您会发现架构更容易处理,并且您可以对每个文档中的两个值进行索引,如下所示:

> db.test.insert({field: [{a:1, b:2}, {a:3, b:4}]})
> db.test.ensureIndex({"field.a":1})
> db.test.ensureIndex({"field.b":1})
> db.test.getIndexes()
[
        {
                "v" : 1,
                "key" : {
                        "_id" : 1
                },
                "ns" : "test.test",
                "name" : "_id_"
        },
        {
                "v" : 1,
                "key" : {
                        "field.a" : 1
                },
                "ns" : "test.test",
                "name" : "field.a_1"
        },
        {
                "v" : 1,
                "key" : {
                        "field.b" : 1
                },
                "ns" : "test.test",
                "name" : "field.b_1"
        }
]
> db.test.find({"field.a": 3})
{ "_id" : ObjectId("520e2ec749177daf439a2ff6"), "field" : [ { "a" : 1, "b" : 2 }, { "a" : 3, "b" : 4 } ] }

您可以运行解释以查看确实正在使用索引(请参阅光标行)

> db.test.find({"field.a": 3}).explain()
{
        "cursor" : "BtreeCursor field.a_1",
        "isMultiKey" : true,
        "n" : 1,
        "nscannedObjects" : 1,
        "nscanned" : 1,
        "nscannedObjectsAllPlans" : 1,
        "nscannedAllPlans" : 1,
        "scanAndOrder" : false,
        "indexOnly" : false,
        "nYields" : 0,
        "nChunkSkips" : 0,
        "millis" : 0,
        "indexBounds" : {
                "field.a" : [
                        [
                                3,
                                3
                        ]
                ]
        },
        "server" : "xxxxx-PC:27017"
}
于 2013-08-16T13:55:03.313 回答