InvalidDocument: Unable to encode object: ObjectId ('51861bc79bb6550f2b98be23')

I have been using mongo for a long time (with python, mongo 2.4.4 64 bit, OS X 10.8.2, pymongo 2.5.2, python 2.7.2) and I have observed strange behavior. Sometimes when you try to insert a document into the collection, the following exception occurs:

Unable to encode object: ObjectId ('51861bc79bb6550f2b98be23')

... "/Users/nutrina/www/env_pdf_admin_apache/lib/python2.7/site-packages/pymongo/collection.py", line 266, in save return self.insert (to_save, manipulate, safe, check_keys, ** kwargs) File "/Users/nutrina/www/env_pdf_admin_apache/lib/python2.7/site-packages/pymongo/collection.py", line 357, insert continue_on_error, self .__ uuid_subtype), safe) InvalidDocument: cannot encode object: ObjectId ('51861bc79bb6550f2b98be23')

I have no idea why this is happening. Has anyone else come across this error, or someone has an idea of ​​what might cause this?

Update: The object I'm trying to save has the following structure:

{ 'is_open': true, // boolean 'data': { 'user_id': ObjectId(...), // ObjectId 'user_type': 1, // Integer } } 

The error is indicated in the * user_id * field, but I am sure that the value is a valid ObjectId. This is the "_id" of the object (user) from another collection (users). And the save operation succeeds in the same value most of the time.

Thanks Gerald

+7
python mongodb pymongo
source share
2 answers

Python integers are stored as arbitrary precision numbers that are not supported by Mongodb. First you need to convert them to regular int64 or string objects.

+10
source share

If you are not using your own type in your document (string, integer, date, boolean, etc.), you need to make sure that it is encoded correctly. If you incorrectly encode non-standard data types, do not guarantee that they can be inserted into PyMongo. You are probably facing an edge case when he refuses to build a new object in a PyMongo document.

PyMongo: Custom Types

+1
source share

All Articles