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 } ]