【发布时间】:2012-09-16 10:15:48
【问题描述】:
我正在尝试查找有关如何在 Mongoosejs 中创建多字段索引的文档,但无济于事。特别是我有两个需要索引和唯一的字段。将两个字段索引在一起的示例猫鼬模式是什么?
【问题讨论】:
我正在尝试查找有关如何在 Mongoosejs 中创建多字段索引的文档,但无济于事。特别是我有两个需要索引和唯一的字段。将两个字段索引在一起的示例猫鼬模式是什么?
【问题讨论】:
您在Schema 对象上调用index 方法来执行此操作,如here 所示。对于你的情况,它会是这样的:
mySchema.index({field1: 1, field2: 1}, {unique: true});
【讨论】:
1 上升,-1 下降。
index的调用中的对象中列出的字段顺序。
1 和 -1 在索引字段上指定升序或降序索引键。我找到了文档http://mongodb.github.io/node-mongodb-native/2.1/tutorials/create-indexes/
在创建复合索引时,必须在架构级别定义索引。
animalSchema.index({ name: 1, type: -1 });
【讨论】:
Following command can be used to create compound index for nested json:
db.ACCOUNT_collection.createIndex({"account.id":1,"account.customerId":1},{unique:1})
Mongo json structure is like :
{"_id":"648738"
"account": {
"id": "123",
"customerId": 7879,
"name": "test"
..
..
}
}
我已经使用示例数据进行了测试,它完全可以按预期工作。
【讨论】:
顺便说一句,接受的答案是错误的,根据https://stackoverflow.com/a/52553550/129300,您应该将字段名称用单引号括起来,即:
mySchema.index({'field1': 1, 'field2': 1}, {unique: true});
快乐的一天!
【讨论】:
field1 和 field2 是有效标识符。例如,field1.foo 不是。