105

我正在尝试查找有关如何在 Mongoosejs 中创建多字段索引的文档,但无济于事。特别是我有两个需要索引和唯一的字段。将两个字段索引在一起的示例猫鼬模式是什么?

4

4 回答 4

225

您调用对象index上的方法来执行Schema操作,如此处所示。对于您的情况,它将类似于:

mySchema.index({field1: 1, field2: 1}, {unique: true});
于 2012-09-24T22:53:13.060 回答
12

创建复合索引时,必须在模式级别定义索引。

animalSchema.index({ name: 1, type: -1 });

参考: http: //mongoosejs.com/docs/guide.html#indexes

于 2014-04-09T23:18:47.390 回答
-4
    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"
   ..
   ..

  }
}

我已经用样本数据进行了测试,它完全可以按预期工作。

于 2018-04-23T05:47:17.920 回答
-5

顺便说一句,接受的答案是错误的,根据https://stackoverflow.com/a/52553550/129300您应该将字段名称用单引号括起来,即:

mySchema.index({'field1': 1, 'field2': 1}, {unique: true});

愉快的一天!

于 2020-03-19T00:48:26.093 回答