mongoose为字段添加索引


MongoDB在读取数据时,如果没有索引,会扫描集合中的每个文件并选取那些符合查询条件的记录。

添加合适的索引能够极大的提高查询的效率

let fileStatus = new Schema({
    materials: String,
    geometries: String,
    guid: {
        type: String,
        index: true,
    }, 
    size: Number,
    path: String,
});

添加后启动node服务可能会出现如下提醒

(node:9764) DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead.

解决的方法:

在连接前添加

mongoose.set("useCreateIndex", true);
mongoose.connect(link, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    poolSize: 1000,
});

查看索引

> db.getCollection("status").getIndexes()
[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "abc.status"
        },
        {
                "v" : 2,
                "key" : {
                        "guid" : 1
                },
                "name" : "guid_1",
                "ns" : "abc.status",
                "background" : true
        }
]

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM