要限制记录数,请在MongoDB中使用$limit。让我们创建一个包含文档的集合-
> db.demo240.insertOne({"StudentName":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e441d969af932883c61ea3c") } > db.demo240.insertOne({"StudentName":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5e441d9a9af932883c61ea3d") } > db.demo240.insertOne({"StudentName":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e441d9d9af932883c61ea3e") } > db.demo240.insertOne({"StudentName":"Mike"}); { "acknowledged" : true, "insertedId" : ObjectId("5e441da19af932883c61ea3f") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo240.find();
这将产生以下输出-
{ "_id" : ObjectId("5e441d969af932883c61ea3c"), "StudentName" : "Chris" } { "_id" : ObjectId("5e441d9a9af932883c61ea3d"), "StudentName" : "Bob" } { "_id" : ObjectId("5e441d9d9af932883c61ea3e"), "StudentName" : "David" } { "_id" : ObjectId("5e441da19af932883c61ea3f"), "StudentName" : "Mike" }
以下是限制MongoDB中记录数的查询-
> db.demo240.aggregate( { $limit : 3 });
这将产生以下输出-
{ "_id" : ObjectId("5e441d969af932883c61ea3c"), "StudentName" : "Chris" } { "_id" : ObjectId("5e441d9a9af932883c61ea3d"), "StudentName" : "Bob" } { "_id" : ObjectId("5e441d9d9af932883c61ea3e"), "StudentName" : "David" }