从 MongoDB 文档集合中获取最大标记记录

mongodbdatabasebig data analytics更新于 2026/1/10 15:22:17

要限制记录数量,请在 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" }

相关文章