In MongoDB, how to return only part of an array?

Consider the "fruit" collection in which I have this document (I use the Python pymongo driver, btw):

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

Now, if I want to get only the "country" 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 I really need a list of several countries, but not all of them, so I use "$ slice" instead of a simple 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, the number of countries has declined, but now it gives me a lot of other unrelated information!

Q: Is there a way to show only the fields that I requested? In addition, the exception "_id" as an exception is fine because this field is always displayed, but I cannot be sure of the other fields, since MongoDB has no schema, and I intend to use this function to add additional fields if necessary.

+4
source share
2 answers

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

Same:

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

If this does not work, I suggest filing an error with mongo. They really respond very well to mistakes.

+11
source

This is strange because this is not a behavior when working in the mongo console.

Have you tried putting 'lemons' in curly braces so that it is JSON syntax?

 find_one({'_id':'lemons'}, { 'countries' : 1, '_id' : 0 }) 

It seems to me that it applies your $ slice projection to all fields, so this might be some weird syntax problem with the pymongo driver

0
source

All Articles