db.factories.insert( { name: "xyz", metro: { city: "New York", state: "NY" } } );
db.factories.ensureIndex( { metro : 1 } );
// this query can use the above index:
db.factories.find( { metro: { city: "New York", state: "NY" } } );
// this one too, as {city:"New York"} < {city:"New York",state:"NY"}
db.factories.find( { metro: { $gte : { city: "New York" } } } );
// this query does not match the document because the order of fields is significant
db.factories.find( { metro: { state: "NY" , city: "New York" } } );
将文档作为关键字的替代方法是建立一个组合索引:
db.factories.ensureIndex( { "metro.city" : 1, "metro.state" : 1 } );
// these queries can use the above index:
db.factories.find( { "metro.city" : "New York", "metro.state" : "NY" } );
db.factories.find( { "metro.city" : "New York" } );
db.factories.find().sort( { "metro.city" : 1, "metro.state" : 1 } );
db.factories.find().sort( { "metro.city" : 1 } )
这两种方法各有优缺点。当使用整个(子)文档作为一个关键字,比较顺序是预定义的并且是以关键字在BSON文档出现的升序来排序的。在组合索引中,你可以混合升序和降序的关键字,查询优化器还是可以只使用索引中的第一个关键字进行查询。 组合索引
除了基本的单个关键字索引外,Mongodb还支持多建“组合”索引。正如基本索引那样,你可以在shell中使用ensureIndex()来创建组合索引,但不像基本索引仅可以指定一个关键字,此时你可以指定多个:
db.things.ensureIndex({firstname: 1}, {unique: true});
db.things.save({lastname: "Smith"});
// Next operation will fail because of the unique index on firstname.
db.things.save({lastname: "Jones"});
dropDups
如果在某个字段已经存在重复值,那么将不能在该字段建立唯一索引。如果无论如何你都要建立唯一索引,并且仅保留数据库中在该字段第一个出现的文档然后删除所有在该字段有重复值的文档,请增加“dropDups”选项: