简体   繁体   中英

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!!!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM