Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 978
Art Avatar asked Jul 21 '12 20:07

Art


1 Answers

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.

like image 56
Gates VP Avatar answered Sep 29 '22 22:09

Gates VP