Search code examples
mongodbaggregation-frameworkmongodb4.0

MongoDB 4.2 - Returns the first n elements from an array


In MongoDB 5.2, there is a function called $firstN. Is there any alternate function or any other way to find the first n elements from a given array in MongoDB 4.2?

Sample document:

{
    "id": 1234,
    "products": [
      {
        "productId": 111,
        "path": "H"
      },
      {
        "productId": 112,
        "path": "H"
      },
      {
        "productId": 113,
        "path": "P"
      }
    ]
}

I want to return the first n product objects from the product array.

With MongoDB 5.2, I can solve this Mongo playground.


Solution

  • Use $slice operator with a similar functionality to take the nth element.

    db.collection.aggregate([
      {
        "$project": {
          "firstFiveProducts": {
            "$slice": [
              "$products",
              5
            ]
          }
        }
      }
    ])
    

    Demo @ MongoPlayground