为此,请使用$ slice。让我们创建一个包含文档的集合-
> db.demo594.insertOne( ... { ... id:1, ... details:[ ... {Name:"Chris",Age:21}, ... {Name:"Bob",Age:20}, ... {Name:"David",Age:23}, ... {Name:"Sam",Age:22} ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e933459fd2d90c177b5bcdd") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo594.find();
这将产生以下输出-
{ "_id" : ObjectId("5e933459fd2d90c177b5bcdd"), "id" : 1, "details" : [ { "Name" : "Chris", "Age" : 21 }, { "Name" : "Bob", "Age" : 20 }, { "Name" : "David", "Age" : 23 }, { "Name" : "Sam", "Age" : 22 } ] }
以下是查询以限制字段的返回值-
> db.demo594.find({}, {"Name": 1, "details": { "$slice": 1}});
这将产生以下输出-
{ "_id" : ObjectId("5e933459fd2d90c177b5bcdd"), "details" : [ { "Name" : "Chris", "Age" : 21 } ] }