Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | 51CTO学院 | CSDN程序员研修院 | OSChina 博客 | 腾讯云社区 | 阿里云栖社区 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏多维度架构

13.12. Indexes 索引

增加索引:1(ascending),-1(descending)

13.12.1. 查看索引

		
db.getCollection('product').getIndexes() 		
		
		
		
[
    {
        "v" : 2,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "netkiller.product"
    },
    {
        "v" : 2,
        "unique" : true,
        "key" : {
            "uuid" : 1
        },
        "name" : "uuid",
        "ns" : "netkiller.product",
        "sparse" : true
    },
    {
        "v" : 2,
        "key" : {
            "nfc" : 1
        },
        "name" : "nfc",
        "ns" : "netkiller.product"
    },
    {
        "v" : 2,
        "unique" : true,
        "key" : {
            "qrcode" : 1
        },
        "name" : "qrcode",
        "ns" : "netkiller.product",
        "sparse" : true
    },
    {
        "v" : 2,
        "key" : {
            "memberId" : 1
        },
        "name" : "memberId",
        "ns" : "netkiller.product"
    },
    {
        "v" : 2,
        "unique" : true,
        "key" : {
            "transactionId" : 1
        },
        "name" : "transactionId",
        "ns" : "netkiller.product",
        "sparse" : true
    }
]		
		
		

查看索引信息

		
db.logging.getIndexes()
[
	{
		"v" : 1,
		"key" : {
			"_id" : 1
		},
		"ns" : "logging.logging",
		"name" : "_id_"
	}
]		
		
		

查看索引名与排序方式

		
db.getCollection('member').getIndexKeys();

[
    {
        "_id" : 1
    },
    {
        "mobile" : 1
    },
    {
        "username" : 1
    },
    {
        "wechat" : 1
    }
]
		
		
		

13.12.2. 创建索引

增加索引

		
db.foo.ensureIndex({firstname: 1, lastname: 1}, {unique: true});		
		
		

索引子对象

		
db.logging.users.ensureIndex({address.city:1})
		
		

13.12.3. 删除索引

		
db.getCollection('product').dropIndex("memberId")		
		
		

根据索引名删除索引

		
> db.logging.users.dropIndex('name_1')
{ "nIndexesWas" : 2, "ok" : 1 }

> db.logging.users.getIndexKeys()
[ { "_id" : 1 } ]
		
		

13.12.4. 唯一索引

		
db.members.createIndex( { "user_id": 1 }, { unique: true } )		
		
		
		
> db.apple.createIndex({"devicetoken":1},{unique: true})
{
	"createdCollectionAutomatically" : false,
	"numIndexesBefore" : 1,
	"numIndexesAfter" : 2,
	"ok" : 1
}
		
		

13.12.5. 复合索引

		
db.getCollection('foo').ensureIndex({"address":1,"phone":1})		
		
		

13.12.6. 稀疏索引

		
db.getCollection('article').ensureIndex({"uuid": 1}, {"unique": true,"sparse":true});
		
		

作用, 唯一索引只允许一条索引字段为空的记录存在,之后就不允许插入了。再次插入为 null 的记录时会报错:

		
E11000 duplicate key error index: dup key: { : null };	
		
		

“sparse”的作用就是当 uuid 在文档中不存在,或为空值,则不进入索引,从而避免上述问题。