在 Mongoose / MongoDB 中创建多字段索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12573753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 12:51:08  来源:igfitidea点击:

Creating Multifield Indexes in Mongoose / MongoDB

mongodbmongoose

提问by Dan

I'm trying to find documentation, to no avail, on how to create multi-field indexes in Mongoosejs. In particular I have two fields that need to be indexed and unique. What is an example mongoose schema that indexes two fields together?

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

回答by JohnnyHK

You call the indexmethod on your Schemaobject to do that as shown here. For your case it would be something like:

您调用index您的方法Schema的对象要做到这一点,如图在这里。对于您的情况,它将类似于:

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

回答by Krumb

Defining indexes at the schema level is necessary when creating compound indexes.

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

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

Reference: http://mongoosejs.com/docs/guide.html#indexes

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

回答by Fer Martin

By the way, the accepted answer is wrong, as per https://stackoverflow.com/a/52553550/129300you should wrap the field names in single quotes, ie:

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

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

Happy Day!

愉快的一天!

回答by Rajeev Rathor

    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"
   ..
   ..

  }
}

I have tested with sample data it is perfectly working as expected.

我已经用示例数据进行了测试,它完全按预期工作。