What is the correct way to query MongoDB for _id using string by using Python?

前端 未结 5 1631
闹比i
闹比i 2021-02-05 02:00

I am using pymongo driver. Supposedly, one can use a string to query the _id field of a document, like this:

thing = db.things.find_one({\'_id\':\'4ea113d6b6848         


        
相关标签:
5条回答
  • 2021-02-05 02:21

    It should be :

    from pymongo.objectid import ObjectId   
    thing = db.things.find_one({'_id': ObjectId('4ea113d6b684853c8e000001') })
    

    EDIT: The current import is: from bson.objectid import ObjectId

    0 讨论(0)
  • 2021-02-05 02:21

    thing = db.things.find_one({'_id':ObjectId('4ea113d6b684853c8e000001')}) should work

    0 讨论(0)
  • 2021-02-05 02:28

    To print it:

    import pymongo
    from bson.objectid import ObjectId    
    print(db.things.find_one({'_id': ObjectId('4ea113d6b684853c8e000001')}))
    

    if you don't want to print, store in other variable

    0 讨论(0)
  • 2021-02-05 02:35

    PyMongo documentation does not seem to be in sync with the current version. ObjectIds are now under bson.objectid namespace. If I remember right, they have been that way since version 2.3. Use from bson.objectid import ObjectId.

    0 讨论(0)
  • 2021-02-05 02:40

    PyMongo has changed its structure. ObjectID is no longer imported from pymongo, but from bson. It should now be:

    from bson.objectid import ObjectId
    thing = db.things.find_one({'_id': ObjectId('4ea113d6b684853c8e000001')})
    

    As a reminder, per pypi/pymongo, do not install the “bson” package. PyMongo comes with its own bson package; doing “pip install bson” installs a third-party package that is incompatible with PyMongo.

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