Removing _id element from Pymongo results

后端 未结 3 1941
挽巷
挽巷 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:20

    Above answer fails if we want specific fields and still ignore _id. Use the following in such cases:

    db.collection.find({'required_column_A':1,'required_col_B':1, '_id': False})
    
    0 讨论(0)
  • 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}
    
    0 讨论(0)
  • 2021-02-01 03:45

    To exclude the _id field in a find query in pymongo, you can use:

    db.collection.find({}, {'_id': False})
    

    The documentation is somewhat missleading on this as it says the _id field is always included. But you can exclude it like shown above.

    0 讨论(0)
提交回复
热议问题