Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

pymongo - In MongoDB how to return only part of array?

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']}

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!

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Like so:

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...