gpt4 book ai didi

mongodb - Mongoose Schema 中索引的用途

转载 作者:可可西里 更新时间:2023-11-01 09:57:00 34 4
gpt4 key购买 nike

我正在尝试在集合中添加独特的文档。但是问题是我想根据 2 个字段来确定唯一性。所以我在网上找到了解决方案。令我困惑的是,INDEX 的目的是什么?在 RDBMS 中,索引通常用于行 ID,这是什么意思,它如何影响唯一性?

var patientSchema = mongoose.Schema({
name : String,
fatherOrHusbandName : String,
address : String,
});


patientSchema .***index***({ email: 1, sweepstakes_id: 1 }, { unique: true });

最佳答案

Indexes support the efficient execution of queries in MongoDB. Without indexes, MongoDB must perform a collection scan, i.e. scan every document in a collection, to select those documents that match the query statement. If an appropriate index exists for a query, MongoDB can use the index to limit the number of documents it must inspect.

有关更多详细信息,请参阅 this documentation .

阅读本文档后不要感到困惑,因为本文档使用 createIndex 而您的代码使用 indexcreateIndex 用于 MongoDBindex 用于内部执行 MongoDB 操作的 mongoose

如果您的数据库中没有数据,那么它可以正常工作

patientSchema .index({ email: 1, sweepstakes_id: 1 }, { unique: true });

但是如果数据库中有一些数据有重复项,那么您应该使用 dropDups 关键字使其成为唯一索引。

但是在使用 dropDups 之前你应该知道一件事。如果您使用 dropDups: true 并且您有一些具有重复值的数据,则在您的数据库中保留一个文档,所有其他数据将被删除(重复数据)。

喜欢:

patientSchema .index({ email: 1, sweepstakes_id: 1 }, { unique: true, dropDups: true });

关于mongodb - Mongoose Schema 中索引的用途,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36822937/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com