Denis
Denis

Reputation: 7343

How to search document by oid in mongoengine

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

Upvotes: 17

Views: 25988

Answers (4)

Saman Pour
Saman Pour

Reputation: 586

This thread is old, but in case someone looks at it around 2022: This works fine with MongoDB Atlas + Mongoengine == 0.23.1

from bson.objectid import ObjectId
Doc.objects(_id=ObjectId("85a2c854002c893dd7756b5g"))

Upvotes: 1

luisdaniel
luisdaniel

Reputation: 917

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.

Upvotes: 8

josephmisiti
josephmisiti

Reputation: 9974

How about just using the raw string:

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

That is probably the easiest way ... right ?

Upvotes: 24

Ross
Ross

Reputation: 18111

This should work:

Docs.objects(pk='4f4381f4e779897a2c000009')

Upvotes: 31

Related Questions