mongodb索引 复合索引

当我们的查询条件不只有一个时,就需要建立复合索引,比如插入一条{x:1,y:2,z:3}记录,按照我们之前建立的x为1的索引,可是使用x查询,现在想按照x与y的值查询,就需要创建如下的索引
 
 
创建复合索引
> db.test2.ensureIndex({x:1,y:1})
{
    "createdCollectionAutomatically" : false,
    "numIndexesBefore" : 2,
    "numIndexesAfter" : 3,
    "ok" : 1
}

查询索引

> db.test2.getIndexes()
[
    {
        "v" : 2,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "config.test2"
    },
    {
        "v" : 2,
        "key" : {
            "x" : 1
        },
        "name" : "x_1",
        "ns" : "config.test2"
    },
    {
        "v" : 2,
        "key" : {
            "x" : 1,
            "y" : 1
        },
        "name" : "x_1_y_1",
        "ns" : "config.test2"
    }
]
看到,新建成功,有三个索引了
再以{x:1,y:1}为条件查询
> db.test2.find({x:1,y:2})
{ "_id" : ObjectId("5b6235d23fb2bed9140233fd"), "x" : 1, "y" : 2, "z" : 3 }
原文地址:https://www.cnblogs.com/wzndkj/p/9404961.html