"projection=" doesn't work in pymongo.collection.Collection.find (pymongo 3.2.2)

681 views
Skip to first unread message

specter119

unread,
Apr 29, 2016, 3:56:07 PM4/29/16
to mongodb-user

Python version : 2.7.11
Pymongo version : 3.2.2

As is showed in official documentation

projection= [list] or {dict} will limit the output of find(), but in my script filter always works, but projection never works, no matter a list or a dict.

I don’t know how to set the projection to limit the output of find(). Who can give me an example?

Kevin Adistambha

unread,
May 3, 2016, 2:04:10 AM5/3/16
to mongodb-user

Hi,

projection= [list] or {dict} will limit the output of find(), but in my script filter always works, but projection never works, no matter a list or a dict.

I don’t know how to set the projection to limit the output of find(). Who can give me an example?

For example, I have a collection named test which contains a single record:

> db.test.find()
{
  "_id": ObjectId("5727f0f607cba93561357d79"),
  "a": 1,
  "b": 2,
  "c": 3,
  "d": 4,
  "e": 5
}

Using pymongo version 3.2.2, I can use the projection parameter to select the returned fields using an array of field names:

>>> db = pymongo.MongoClient('localhost').test
>>> list(db.test.find(projection=['a','b','c']))
[{u'_id': ObjectId('5727f0f607cba93561357d79'),
  u'a': 1.0,
  u'b': 2.0,
  u'c': 3.0}]

If you need to exclude fields instead, you need to use the dictionary form of projection:

>>> list(db.test.find(projection={'_id':0}))
[{u'a': 1.0, u'b': 2.0, u'c': 3.0, u'd': 4.0, u'e': 5.0}]

Best regards,
Kevin

Reply all
Reply to author
Forward
0 new messages