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