0

Here is my table:

    {
        "_id" : ObjectId("5f2e8e0d4976ed2c04fc2e90"),
        "reference" : "5f2e8e0d4976ed2c04fc2e8f",
        "id" : "5e87187f6e8c15766e6994f8",
        "name" : "no name",
        "items" : [
                {
                        "_id" : ObjectId("5f2e994336caf138c13560fc"),
                        "requestedItems" : "5e87187f6e8c15766e6994f8",
                        "name" : "no name",
                },
                {
                        "_id" : ObjectId("5f2e994336caf138c135601c"),
                        "requestedItems" : "5e87187f6e8c15766e6994f8",
                        "name" : "no name",
                },
                {
                        "_id" : ObjectId("5f2e994336caf138c135201c"),
                        "requestedItems" : "5e87187f6e8c15766e6994f8",
                        "name" : "no name",
                },
                {
                        "_id" : ObjectId("5f2e994336caf138c139521c"),
                        "requestedItems" : "5e87187f6e8c15766e6994f8",
                        "name" : "no name",
                },
                {
                        "_id" : ObjectId("5f2e994336caf138c139504f"),
                        "requestedItems" : "5e87187f6e8c15766e6994f8",
                        "name" : "no name",
                },

        ],
        "createdAt" : ISODate("2020-08-08T11:35:41.675Z"),
        "updatedAt" : ISODate("2020-08-18T13:34:43.077Z"),
        "date" : "8-8-2020",
        "__v" : 0
}

I am looking to query only the last three sub-documents in "ITEMS" I have been trying MongoDB aggregate framework but had no success. Here is what I have come up with. Any help out there would be very much appreciated.

    reqInventory.aggregate([
 {$match:{"id" : "5e87187f6e8c15766e6994f8"}},
  { $addFields: {
    items: {
      $map: {
        input: '$items',
        as: 'new',
        in: {
          requestedItems : '$$new.requestedItems',
          name : '$$new.name',
          items: { $slice: [ '$$new.items', 3 ] }
          
        }
      }
    }
  }}
Ravi Garg
  • 1,378
  • 12
  • 23
TAG
  • 49
  • 7

3 Answers3

1

You can just use $slice direct in array field with negative count,

reqInventory.aggregate([
  {
    $match: { "id": "5e87187f6e8c15766e6994f8" }
  },
  {
    $addFields: { items: { $slice: ["$items", -3] } }
  }
])

Playground

turivishal
  • 34,368
  • 7
  • 36
  • 59
1

You can directly use project

reqInventory.aggregate([
      {
$match:{"id" : "5e87187f6e8c15766e6994f8"}
},
          {
            '$project': {
              'last3ITems': {
                '$slice': [
                  '$$ROOT.items', 2, 5
                ]
              }
            }
          }
        ]
raga
  • 899
  • 10
  • 14
0

You can use{ $limit: <positive integer> } to limit your responses.

Here is the way which gives you more explanation https://docs.mongodb.com/manual/reference/operator/aggregation/limit/

Ravi Garg
  • 1,378
  • 12
  • 23