Home | 简体中文 | 繁体中文 | 杂文 | 打赏(Donations) | Github | OSChina 博客 | 云社区 | 云栖社区 | Facebook | Linkedin | 知乎专栏 | 视频教程 | About

45.12. Indexes 索引

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

45.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
    }
]
		
		
		

45.12.2. 创建索引

增加索引

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

索引子对象

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

45.12.3. 删除索引

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

根据索引名删除索引

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

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

45.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
}
		
		

45.12.5. 复合索引

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

45.12.6. 稀疏索引

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

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

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

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