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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With