在 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"
}
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP