MongoDB 陣列中 capped 子集合查詢


在 MongoDB 中,您無法對子集合使用 capped。但是,對整體文件使用 capped。若要顯示陣列中的特定數量的值,請使用 $slice。

讓我們建立一個包含文件的集合 -

> db.demo319.insertOne({"Scores":[100,345,980,890]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e50ecf6f8647eb59e562064")
}
> db.demo319.insertOne({"Scores":[903,10004,84575,844]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e50ed01f8647eb59e562065")
}

在集合中顯示所有文件,方法是使用 find() 方法 -

> db.demo319.find().pretty();

這將產生以下輸出 -

{
   "_id" : ObjectId("5e50ecf6f8647eb59e562064"),
   "Scores" : [
      100,
      345,
      980,
      890
   ]
}
{
   "_id" : ObjectId("5e50ed01f8647eb59e562065"),
   "Scores" : [
      903,
      10004,
      84575,
      844
   ]
}

以下是陣列中 capped 子集合的查詢 -

> db.demo319.aggregate([
... { $project: {TwoScores: { $slice: [ "$Scores", 2 ] } } }
... ])

這將產生以下輸出 -

{ "_id" : ObjectId("5e50ecf6f8647eb59e562064"), "TwoScores" : [ 100, 345 ] }
{ "_id" : ObjectId("5e50ed01f8647eb59e562065"), "TwoScores" : [ 903, 10004 ] }

更新於: 2020-04-02

358 瀏覽量

開啟 職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.