Irfan Habib
Irfan Habib

Reputation: 158

how to return sliced element from an mongodb array?

I have a list of data in an array of size 250 MB. Every time when I query, the full 250 data is downloaded even I am slicing the data. here is my code

DomainsApi.findOne({}, {auction_list:{$slice:[10, 20]}}, (err, doc)=>{
  if(doc){
    console.log(doc)
  }
})

I want only 10 item from the auction_list array but its not working. the full 250 MB data is downloading everytime and eating my bandwidth and time.

I checked the mongodb docs but that didn't help me.

How can I achieve that? I am on node js and using mongodb atlas free account. Thanks in Advance

Upvotes: 1

Views: 240

Answers (1)

Murat Colyaran
Murat Colyaran

Reputation: 2189

I'd suggest you to use aggregate. Check this please:

db.collection.aggregate([
  {
    $project: {
      _id: 0,
      slicedArray: {
        $slice: [
          "$auction_list",
          10
        ]
      }
    }
  }
])

Playground

Upvotes: 2

Related Questions