在MongoDB中如何仅返回数组的一部分? [英] In MongoDB how to return only part of array?

查看:875
本文介绍了在MongoDB中如何仅返回数组的一部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑收集水果",在其中有此文档(我正在使用Python的pymongo驱动程序btw):

Consider collection "fruits", in which I have this document (I'm using Python's pymongo driver, btw):

{
    '_id'       : 'lemons',
    'weight'    : 58,
    'shape'     : 'oval',
    'countries' : ['Mexico', 'Turkey', 'Argentina', 'SAfrica', 'US']
}

现在,如果我只想获取国家/地区"字段,则此查询可以正常运行:

Now, if I want to get only the 'countries' field, this query works just fine:

In [1]: find_one('lemons', { 'countries' : 1, '_id' : 0 })
Out[1]: {u'countries': [u'Mexico', u'Turkey', u'Argentina', u'SAfrica', u'US']}

但是事实证明,我真正需要的只是一些顶级国家的列表,而不是全部,因此我使用的是"$ slice",而不是普通的True/1:

But it turns out that what I really need is just list of few top-countries, not all of them, so I'm using "$slice" instead of plain True/1:

In [239]: c.find_one('lemons', { 'countries' : { '$slice' : [0, 3] }, '_id' : 0 })
Out[239]: 
{u'countries': [u'Mexico', u'Turkey', u'Argentina'],
 u'shape': u'oval',
 u'weight': 58}

好吧,国家的数量在减少,但是现在它给了我很多其他不相关的信息!

Well, number of countries has shrinked, but now it gives me whole lot of other unrelated information!

问:有什么方法可以只显示我要求的字段?另外,将'_id'列为例外是可以的,因为总是显示此字段,但是我不确定其他字段,因为MongoDB是无方案的,我打算在需要时使用此功能添加其他字段.

Q: Is there any way to show only those fields that I have asked for? Additionally listing '_id' as exception is fine, because this field is always presented, but I can't be sure about other fields, since MongoDB is scheme-less and I intend to use this feature to add additional fields if needed.

推荐答案

您是否尝试过添加其他包含投影?我认为您也许可以添加一些琐碎的内容,例如foo:1(这不是真实字段),并且应该可以使用.

Have you tried adding another inclusion projection? I think you may be able to add something trivial like foo:1 (that is not a real field) and it should work.

像这样:

{ 'countries' : { '$slice' : [0, 3] }, '_id' : 0, foo : 1 }

如果它不起作用,我建议向mongo提交错误.实际上,他们对错误的响应非常好.

If it doesn't work I suggest filing a bug with mongo. They are actually very good about responding to bugs.

这篇关于在MongoDB中如何仅返回数组的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆