要搜索范围,sort()
与limit()
结合使用。让我们创建一个包含文档的集合-
> db.demo665.insertOne({"Value":10}); { "acknowledged" : true, "insertedId" : ObjectId("5ea1bf1424113ea5458c7d08") } > db.demo665.insertOne({"Value":15}); { "acknowledged" : true, "insertedId" : ObjectId("5ea1bf1b24113ea5458c7d09") } > db.demo665.insertOne({"Value":55}); { "acknowledged" : true, "insertedId" : ObjectId("5ea1bf1e24113ea5458c7d0a") } > db.demo665.insertOne({"Value":25}); { "acknowledged" : true, "insertedId" : ObjectId("5ea1bf2324113ea5458c7d0b") } > db.demo665.insertOne({"Value":20}); { "acknowledged" : true, "insertedId" : ObjectId("5ea1bf2b24113ea5458c7d0c") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo665.find();
这将产生以下输出-
{ "_id" : ObjectId("5ea1bf1424113ea5458c7d08"), "Value" : 10 } { "_id" : ObjectId("5ea1bf1b24113ea5458c7d09"), "Value" : 15 } { "_id" : ObjectId("5ea1bf1e24113ea5458c7d0a"), "Value" : 55 } { "_id" : ObjectId("5ea1bf2324113ea5458c7d0b"), "Value" : 25 } { "_id" : ObjectId("5ea1bf2b24113ea5458c7d0c"), "Value" : 20 }
以下是在MongoDB中搜索范围的查询-
> db.demo665.find({Value:{$lte:30}}).sort({Value:-1}).limit(2);
这将产生以下输出-
{ "_id" : ObjectId("5ea1bf2324113ea5458c7d0b"), "Value" : 25 } { "_id" : ObjectId("5ea1bf2b24113ea5458c7d0c"), "Value" : 20 }