MongoDB 限制记录
-
限制记录
在本章中,我们将学习如何使用MongoDB限制记录。 -
limit()方法
要限制MongoDB中的记录,您需要使用limit()方法。该方法接受一个数字类型参数,该参数是您要显示的文档数。带限制记录的find()方法的基本语法如下->db.COLLECTION_NAME.find().limit(NUMBER)
示例考虑集合empDetails具有以下数据-db.empDetails.find(); { "_id" : ObjectId("5f48781a17adfc074ccae0e7"), "title" : "Java 教程", "author" : "张三", "phone" : "10086" } { "_id" : ObjectId("5f48781a17adfc074ccae0e8"), "title" : "PHP 教程", "author" : "李四", "phone" : "10086" } { "_id" : ObjectId("5f48781a17adfc074ccae0e9"), "title" : "Python 教程", "author" : "王五", "phone" : "19999999999" }
以下示例在查询文档时将仅显示两个文档。> db.empDetails.find(); # 没有limit前 { "_id" : ObjectId("5f48781a17adfc074ccae0e7"), "title" : "Java 教程", "author" : "张三", "phone" : "10086" } { "_id" : ObjectId("5f48781a17adfc074ccae0e8"), "title" : "PHP 教程", "author" : "李四", "phone" : "10086" } { "_id" : ObjectId("5f48781a17adfc074ccae0e9"), "title" : "Python 教程", "author" : "王五", "phone" : "19999999999" } > db.empDetails.find().limit(2); # limit后 { "_id" : ObjectId("5f48781a17adfc074ccae0e7"), "title" : "Java 教程", "author" : "张三", "phone" : "10086" } { "_id" : ObjectId("5f48781a17adfc074ccae0e8"), "title" : "PHP 教程", "author" : "李四", "phone" : "10086" }
如果您未在limit()方法中指定number参数,则它将显示集合中的所有文档。
-
skip()方法
除了limit()方法外,还有另一种方法skip(),它也接受数字类型参数,并用于跳过文档数。带限制记录和跳过文档数的find()方法的基本语法如下->db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)
示例考虑集合empDetails具有以下数据-db.empDetails.find(); { "_id" : ObjectId("5f48781a17adfc074ccae0e7"), "title" : "Java 教程", "author" : "张三", "phone" : "10086" } { "_id" : ObjectId("5f48781a17adfc074ccae0e8"), "title" : "PHP 教程", "author" : "李四", "phone" : "10086" } { "_id" : ObjectId("5f48781a17adfc074ccae0e9"), "title" : "Python 教程", "author" : "王五", "phone" : "19999999999" }
以下示例将跳过第一条仅显示第二个文档。db.empDetails.find(); { "_id" : ObjectId("5f48781a17adfc074ccae0e7"), "title" : "Java 教程", "author" : "张三", "phone" : "10086" } { "_id" : ObjectId("5f48781a17adfc074ccae0e8"), "title" : "PHP 教程", "author" : "李四", "phone" : "10086" } { "_id" : ObjectId("5f48781a17adfc074ccae0e9"), "title" : "Python 教程", "author" : "王五", "phone" : "19999999999" } > db.empDetails.find().limit(1).skip(1); { "_id" : ObjectId("5f48781a17adfc074ccae0e8"), "title" : "PHP 教程", "author" : "李四", "phone" : "10086" }
请注意,skip()方法的默认值为0。