Removing _id element from Pymongo results

后端 未结 3 2016
挽巷
挽巷 2021-02-01 02:44

I\'m attempting to create a web service using MongoDB and Flask (using the pymongo driver). A query to the database returns documents with the \"_id\" field included, of course

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-01 03:39

    You are calling

    del objects['_id']
    

    on the cursor object!

    The cursor object is obviously an iterable over the result set and not single document that you can manipulate.

    for obj in objects:
         del obj['_id']
    

    is likely what you want.

    So your claim is completely wrong as the following code shows:

    import pymongo
    
    c = pymongo.Connection()
    db = c['mydb']
    db.foo.remove({})
    db.foo.save({'foo' : 42})
    
    for row in db.foo.find():
        del row['_id']
        print row
    
    
    
    $ bin/python foo.py 
    
    > {u'foo': 42}
    

提交回复
热议问题