How to search document by oid in mongoengine
Asked Answered
E

4

16

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

Ezarra answered 3/4, 2012 at 6:45 Comment(0)
R
24

How about just using the raw string:

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

That is probably the easiest way ... right ?

Residency answered 16/5, 2012 at 4:22 Comment(1)
Doesn't work for primary key though. Or am I the only one?Collage
T
31

This should work:

Docs.objects(pk='4f4381f4e779897a2c000009')
Tralee answered 3/4, 2012 at 7:25 Comment(2)
This one returns list. Not a single object.Lagerkvist
@Raptor then use .first()Lastminute
R
24

How about just using the raw string:

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

That is probably the easiest way ... right ?

Residency answered 16/5, 2012 at 4:22 Comment(1)
Doesn't work for primary key though. Or am I the only one?Collage
I
8

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.

Ide answered 8/12, 2012 at 21:34 Comment(0)
T
1

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"))
Titre answered 28/11, 2021 at 1:12 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.