在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"
}
}热门推荐
10 小侄过生日祝福语简短
11 小店营业的祝福语简短
12 担任老师的祝福语简短
13 饮料吧台祝福语简短大气
14 公司新春搞笑祝福语简短
15 高情商敬酒祝福语简短
16 婚礼祝福语新郎妹妹简短
17 教师答辩通过祝福语简短
18 生女孩红包简短祝福语