Search code examples
mongodbmongoose

How to get the data in range for a sub property of the transactions


I am trying to achieve pagination. However my collection is a bit different to support the same. Here is how my collection looks:

{
  "_id": {
    "$oid": "63593e8eef21110023a0d970"
  },
  "itemName": "commodity ",
  "date": {
    "$date": {
      "$numberLong": "1666793102984"
    }
  },
  "totalWeight": 4365282,
  "totalBags": 73740,
  "transactions": [
    {
      "_id": {
        "$oid": "63735d89f91c2c0023ce9d1c"
      },
      "kisanName": "fff",
      "kisanID": "632b5246abb36a002354eae8",
      "numberofBags": 19,
      "totalweight": 1163,
      "purchaserId": "6370ea3dac49fa00232f7d65",
      "purchaserName": "ggg",
      "rate": 55,
      "date": {
        "$date": {
          "$numberLong": "1668504969354"
        }
      }
    },
    {
      "_id": {
        "$oid": "637378111da44c0023d0f271"
      },
      "kisanName": "asdf",
      "kisanID": "632b50f6abb36a002354eac0",
      "numberofBags": 15,
      "totalweight": 861,
      "purchaserId": "6370e8c2ac49fa00232f7d3e",
      "purchaserName": "asdff",
      "rate": 59,
      "date": {
        "$date": {
          "$numberLong": "1668511761094"
        }
      }
    },
    
  ],
  "__v": 2128
}

In this, each Commodity has a number of transactions inside, I want to paginate them and return 25 transactions per query, however, my current Mongoose application is a simple collection.find() which returns the commodity and all the transactions inside. instead I want to get commodity and only 25 transactions at a time.

How can we achieve this?


Solution

  • You can simply use $slice on the projection part of the query:

    db.collection.find(
      {_id: {$oid: "63593e8eef21110023a0d970"}},
      {transactions: {$slice: ["$transactions", pageNum * itemsOnPage, itemsOnPage]}}
    )
    

    See how it works on the playground example