MongoDB查询数组中的上限子集合

在MongoDB中,您不能将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
   ]
}

以下是查询数组中的上限子集合-

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

这将产生以下输出-

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