简体   繁体   中英

How do you limit an array subelement in Mongo?

Let's say I have the following data model in Mongo:

{
   _id: ...,
   name: "...",
   obj: {...},
   list: [ ... ],
}

Now let's say, my list array is very long, and I don't want to grab the whole document every time. So I want to get obj and name , but only grab the last 5 elements in list . How do you do this with with Mongo? I'm using pymongo.

I think you are looking for the $slice operator. Docs are here .

The syntax you are looking for is something like this:

db.coll.find({}, {obj:1, name: 1, list:{$slice: -5}}); // last 5

Note that this will also return the _id field by default. If you do not want the _id add _id:0 in front of obj:1 . This is the JS syntax, but the python syntax will be very close.

use $slice operator to limit array elements

GeoLocation.find({},{name: 1, geolocation:{$slice: -5}})
    .then((result) => {
      res.json(result);
    })
    .catch((err) => {
      res.status(500).json({ success: false, msg: `Something went wrong. ${err}` });
});

where geolocation is array of data, from that we get last 5 record.

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