📅  最后修改于: 2020-11-23 00:56:37             🧑  作者: Mango
在MongoDB中,limit()方法用于限制要显示的文档字段。有时,数据库集合中有很多字段,只需要检索1或2。在这种情况下,将使用limit()方法。
MongoDB limit()方法与find()方法一起使用。
句法:
db.COLLECTION_NAME.find().limit(NUMBER)
考虑一个具有集合名称javatpoint的示例。
该集合中包含以下字段。
[
{
Course: "Java",
details: { Duration: "6 months", Trainer: "Sonoo Jaiswal" },
Batch: [ { size: "Medium", qty: 25 } ],
category: "Programming Language"
},
{
Course: ".Net",
details: { Duration: "6 months", Trainer: "Prashant Verma" },
Batch: [ { size: "Small", qty: 5 }, { size: "Medium", qty: 10 }, ],
category: "Programming Language"
},
{
Course: "Web Designing",
details: { Duration: "3 months", Trainer: "Rashmi Desai" },
Batch: [ { size: "Small", qty: 5 }, { size: "Large", qty: 10 } ],
category: "Programming Language"
}
];
在这里,您必须使用limit()方法仅显示一个字段。
db.javatpoint.find().limit(1)
执行后,您将得到以下结果
输出:
{ "_id" : ObjectId("564dbced8e2c097d15fbb601"), "Course" : "Java", "details" : {
"Duration" : "6 months", "Trainer" : "Sonoo Jaiswal" }, "Batch" : [ { "size" :
"Medium", "qty" : 25 } ], "category" : "Programming Language" }
在MongoDB中,skip()方法用于跳过文档。它与find()和limit()方法一起使用。
db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)
在这里还要考虑上面讨论的示例。集合javatpoint具有三个文档。
[
{
Course: "Java",
details: { Duration: "6 months", Trainer: "Sonoo Jaiswal" },
Batch: [ { size: "Medium", qty: 25 } ],
category: "Programming Language"
},
{
Course: ".Net",
details: { Duration: "6 months", Trainer: "Prashant Verma" },
Batch: [ { size: "Small", qty: 5 }, { size: "Medium", qty: 10 }, ],
category: "Programming Language"
},
{
Course: "Web Designing",
details: { Duration: "3 months", Trainer: "Rashmi Desai" },
Batch: [ { size: "Small", qty: 5 }, { size: "Large", qty: 10 } ],
category: "Programming Language"
}
];
执行以下查询以仅检索一个文档并跳过2个文档。
db.javatpoint.find().limit(1).skip(2)
执行后,您将得到以下结果
输出:
{ "_id" : ObjectId("564dbced8e2c097d15fbb603"), "Course" : "Web Designing", "det
ails" : { "Duration" : "3 months", "Trainer" : "Rashmi Desai" }, "Batch" : [ { "
size" : "Small", "qty" : 5 }, { "size" : "Large", "qty" : 10 } ], "category" : "
Programming Language" }
如您所见,skip()方法跳过了第一和第二文档,只显示了第三文档。