【问题标题】:Creating Multifield Indexes in Mongoose / MongoDB在 Mongoose / MongoDB 中创建多字段索引
【发布时间】:2012-09-16 10:15:48
【问题描述】:

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

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    您在Schema 对象上调用index 方法来执行此操作,如here 所示。对于你的情况,它会是这样的:

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

    【讨论】:

    • 这在mongodb中称为Compount Index。因此它将索引创建为 field1 和 field1 + field2。所以它是第一个根据 field1 的索引,然后在 field1 内部相对于字段 2
    • field1:和field2:后面的1是什么意思?
    • @DamonYuan 他们设置了索引中字段的排序顺序。 1 上升,-1 下降。
    • @KetanGhumatkar 它基于对index的调用中的对象中列出的字段顺序。
    • 1-1 在索引字段上指定升序或降序索引键。我找到了文档http://mongodb.github.io/node-mongodb-native/2.1/tutorials/create-indexes/
    【解决方案2】:

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

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

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

    【讨论】:

    【解决方案3】:
        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"
       ..
       ..
    
      }
    }
    

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

    【讨论】:

    • 我们不希望使用 mongooses shell 我们希望使用 node js 架构
    【解决方案4】:

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

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

    快乐的一天!

    【讨论】:

    • JS 中的对象键可以不加引号,只要它们是语法上有效的标识符。 field1field2 是有效标识符。例如,field1.foo 不是。
    猜你喜欢
    • 2021-10-25
    • 2019-12-18
    • 1970-01-01
    • 2017-09-04
    • 2015-03-17
    • 2018-09-01
    • 2014-12-15
    • 2014-07-01
    相关资源
    最近更新 更多