在MongoDB中,获取第一个文档和最后一个文档的最有效方法是什么?
要获取MongoDB中的第一个和最后一个文档,请aggregate()
分别与$first和$last一起使用。让我们创建一个包含文档的集合-
> db.demo73.insertOne({"Name":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e29c41b71bf0181ecc4226c") } . > db.demo73.insertOne({"Name":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5e29c41e71bf0181ecc4226d") } > db.demo73.insertOne({"Name":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e29c42271bf0181ecc4226e") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo73.find();
这将产生以下输出-
{ "_id" : ObjectId("5e29c41b71bf0181ecc4226c"), "Name" : "Chris" } { "_id" : ObjectId("5e29c41e71bf0181ecc4226d"), "Name" : "Bob" } { "_id" : ObjectId("5e29c42271bf0181ecc4226e"), "Name" : "David" }
以下是获取第一个和最后一个文档的方法-
> db.demo73.aggregate({ ... $group: { ... _id: null, ... first: { $first: "$$ROOT" }, ... last: { $last: "$$ROOT" } ... } ... } ... );
这将产生以下输出-
{ "_id" : null, "first" : { "_id" : ObjectId("5e29c41b71bf0181ecc4226c"), "Name" : "Chris" }, "last" : { "_id" : ObjectId("5e29c42271bf0181ecc4226e"), "Name" : "David" } }