MongoDB 中 limit() 会提升查询速度吗?
不,使用 LIMIT() 减少带宽占用,并不会提升查询速度。下面我们通过一个示例,创建一个包含文档的集合 −
> db.demo197.insertOne({"Name":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3afde803d395bdc21346d8") } > db.demo197.insertOne({"Name":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3afdef03d395bdc21346d9") } > db.demo197.insertOne({"Name":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3afdf203d395bdc21346da") } > db.demo197.insertOne({"Name":"Sam"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3afdf603d395bdc21346db") } > db.demo197.insertOne({"Name":"Mike"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3afdf903d395bdc21346dc") } > db.demo197.insertOne({"Name":"Carol"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3afe1603d395bdc21346dd") } > db.demo197.insertOne({"Name":"John"}); { "acknowledged" : true, "insertedId" : ObjectId("5e3afe2003d395bdc21346de") }
通过 find() 方法显示集合中的所有文档 −
> db.demo197.find();
这将产生以下结果 −
{ "_id" : ObjectId("5e3afde803d395bdc21346d8"), "Name" : "Chris" } { "_id" : ObjectId("5e3afdef03d395bdc21346d9"), "Name" : "Bob" } { "_id" : ObjectId("5e3afdf203d395bdc21346da"), "Name" : "David" } { "_id" : ObjectId("5e3afdf603d395bdc21346db"), "Name" : "Sam" } { "_id" : ObjectId("5e3afdf903d395bdc21346dc"), "Name" : "Mike" } { "_id" : ObjectId("5e3afe1603d395bdc21346dd"), "Name" : "Carol" } { "_id" : ObjectId("5e3afe2003d395bdc21346de"), "Name" : "John" }
以下是使用 LIMIT() 的查询 −
> db.demo197.find().limit(4);
这将产生以下结果 −
{ "_id" : ObjectId("5e3afde803d395bdc21346d8"), "Name" : "Chris" } { "_id" : ObjectId("5e3afdef03d395bdc21346d9"), "Name" : "Bob" } { "_id" : ObjectId("5e3afdf203d395bdc21346da"), "Name" : "David" } { "_id" : ObjectId("5e3afdf603d395bdc21346db"), "Name" : "Sam" }
广告