How to search document by oid in mongoengine

▼魔方 西西 提交于 2019-12-12 07:57:50

问题


I need get documents from db by oid, like:

Docs.objects(_id='4f4381f4e779897a2c000009')

But how to do it, if _id requires ObjectId object and even I try to set ObjectId from pymongo it doesn't work.

Docs.objects(_id=pymongo.objectid.ObjectId('4f4381f4e779897a2c000009'))

return empty list


回答1:


How about just using the raw string:

Docs.objects.get(id='4f4381f4e779897a2c000009')

That is probably the easiest way ... right ?




回答2:


This should work:

Docs.objects(pk='4f4381f4e779897a2c000009')



回答3:


Came to this question because I had a lot of trouble with this myself. It seems like PyMongo changed this and objectid is no longer inside pymongo and is now instead:

import bson
Doc.objects.get(id=bson.objectid.ObjectId('4f4381f4e779897a2c000009'))

Also, Mongoengine uses the name 'id' for the ObjectID field.



来源:https://stackoverflow.com/questions/9988352/how-to-search-document-by-oid-in-mongoengine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!