Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB with Mongoose limit subdocuments

I am a noob when it comes to MongoDB and Mongoose so please forgive me...

I am using Node with Express along with Mongoose. I have a document with a ton of subdocuments, so much so that my server runs out of memory when trying to load all the subdocuments. So I want to select the last 30 items of a subdocument. Here is what I have now, and then a guess as to what I think I want...

Device.findOne({ device_id: deviceId }, (err, device) => {
        ....
})

Here is a guess

Device.findOne({ device_id: deviceId }, { movements: { $slice: 30 } }, (err, device) => {
        ....
})

Any help would be awesome, thanks in advance!!!

like image 391
gregwinn Avatar asked Aug 31 '25 23:08

gregwinn


1 Answers

you almost nailed it.

To get the last 30 values, just use minus instead. In your case, you can do something like:

Device.findOne({ device_id: deviceId }, { movements: { $slice: -30 } }, (err, device) => {
        ....
})

Hope it helped.

like image 64
Israel Zinc Avatar answered Sep 03 '25 11:09

Israel Zinc