'How to display only an array's 5 elements from a MongoDB collection?

Introduction

I am trying to make a query that outputs only an array, and within that array outputs only 5 elements of that array. I've gotten them working individually but cannot get them to work together.

Code

Output only array in its entireity:

db.mycoll.find({
    "_id": ObjectId("5b55d0a34270ce58b8bfabcd"),     
    "myarr.platform": "9 and 3 quarters"
},{
    myarr: 1
}).pretty()

Output only 5 elements of array, but also displays other fields:

db.mycoll.find({
    "_id": ObjectId("5b55d0a34270ce58b8bfabcd"),     
    "myarr.platform": "9 and 3 quarters"
},{
    myarr:{ $slice: 5 }
}).pretty()

Any help would be appreciated!



Solution 1:[1]

I found a solution by explicitly setting _id: 1 in the projection. This uses the property of find that if any field is included in the projection, all other fields will be excluded, unless also explicitly included.

db.mycoll.find({
     "_id": ObjectId("5b55d0a34270ce58b8bfabcd"),     
     "myarr.platform": "9 and 3 quarters"
},{
    "myarr" : { $slice: 5 },
    "_id" : 1
}).pretty()

For more, read the note here: https://docs.mongodb.com/manual/reference/method/db.collection.find/#projection

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1