您可以使用$slice运算符来限制数组。让我们创建包含文档的集合。以下是查询
> db.limitAnArrayDemo.insertOne( ... { ... _id: 101, ... "PlayerName": "Bob", ... "PlayerDetails": {Age:23,isStudent:true}, ... "PlayerGameScores": [234,5767,58,67,78,90,1002,576,68,45,23,45,678,89,78 ] ... } ... ); { "acknowledged" : true, "insertedId" : 101 }
以下是在find()
方法的帮助下显示集合中所有文档的查询
> db.limitAnArrayDemo.find().pretty();
这将产生以下输出
{ "_id" : 101, "PlayerName" : "Bob", "PlayerDetails" : { "Age" : 23, "isStudent" : true }, "PlayerGameScores" : [ 234, 5767, 58, 67, 78, 90, 1002, 576, 68, 45, 23, 45, 678, 89, 78 ] }
以下是限制MongoDB中的数组子元素的查询。以下查询将仅显示最后10个元素
> db.limitAnArrayDemo.find({}, {PlayerName:1, PlayerDetails: 1, PlayerGameScores:{$slice: -10}}).pretty();
以下是显示10个PlayerGameScores的输出
{ "_id" : 101, "PlayerName" : "Bob", "PlayerDetails" : { "Age" : 23, "isStudent" : true }, "PlayerGameScores" : [ 90, 1002, 576, 68, 45, 23, 45, 678, 89, 78 ] }