简体   繁体   English

你如何限制Mongo中的数组子元素?

[英]How do you limit an array subelement in Mongo?

Let's say I have the following data model in Mongo: 假设我在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. 现在让我们说,我的list数组非常长,我不想每次都抓取整个文档。 So I want to get obj and name , but only grab the last 5 elements in list . 所以我想获得objname ,但只获取list的最后5个元素。 How do you do this with with Mongo? 你如何使用Mongo做到这一点? I'm using pymongo. 我正在使用pymongo。

I think you are looking for the $slice operator. 我认为你正在寻找$slice运算符。 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. 请注意,默认情况下,这也将返回_id字段。 If you do not want the _id add _id:0 in front of obj:1 . 如果你不想在obj:1前加上_id add _id:0 This is the JS syntax, but the python syntax will be very close. 这是JS语法,但python语法非常接近。

use $slice operator to limit array elements 使用$ slice运算符来限制数组元素

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. geolocation是数据数组,我们得到最后5条记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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