在 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"
   }
}

更新於: 2020 年 3 月 30 日

889 次瀏覽

開啟您的職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.