MongoDB query for capped sub-collection in an array


In MongoDB, you cannot use capped for sub-collection. However, use capped on the overall document. To display a specific number of values from an array, prefer $slice.

Let us create a collection with documents −

> 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")
}

Display all documents from a collection with the help of find() method −

> db.demo319.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5e50ecf6f8647eb59e562064"),
   "Scores" : [
      100,
      345,
      980,
      890
   ]
}
{
   "_id" : ObjectId("5e50ed01f8647eb59e562065"),
   "Scores" : [
      903,
      10004,
      84575,
      844
   ]
}

Following is the query for capped sub-collection in an array −

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

This will produce the following output −

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

Updated on: 02-Apr-2020

316 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements