For this, use $slice. Let us create a collection with documents −
> 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") }
Display all documents from a collection with the help of find() method −
> db.demo594.find();
This will produce the following output −
{ "_id" : ObjectId("5e933459fd2d90c177b5bcdd"), "id" : 1, "details" : [ { "Name" : "Chris", "Age" : 21 }, { "Name" : "Bob", "Age" : 20 }, { "Name" : "David", "Age" : 23 }, { "Name" : "Sam", "Age" : 22 } ] }
Following is the query to limit the returning values of a field −
> db.demo594.find({}, {"Name": 1, "details": { "$slice": 1}});
This will produce the following output −
{ "_id" : ObjectId("5e933459fd2d90c177b5bcdd"), "details" : [ { "Name" : "Chris", "Age" : 21 } ] }