1

I'm working on a mongo database which, for some reason, has the user id stored as ObjectId.

In order to test some functions, I'd like to be able to populate a test database - for example, as follows:

import mongomock
from bson import ObjectId

client = mongomock.MongoClient("mongodb://localhost:27017/test-database")
database = client.get_default_database()
database.test_collection.insert({'_id': ObjectId('my_user_id'), 'value': 'my_value'})

However, running this returns

InvalidId: 'my_user_id' is not a valid ObjectId, it must be a 12-byte input or a 24-character hex string

How can I correctly insert an ObjectId object into my test database, so I can test querying it using

database.test_collection.find_one({'user': ObjectId('my_user_id')})

(which works fine when I query the real database)?

ignoring_gravity
  • 6,677
  • 4
  • 32
  • 65

2 Answers2

1

You need to use, as the InvalidId message states, a 12-byte 'binary' input or a 24-character string of hexadecimal characters.

So, if you wan to use something like 'my_user_id' you'll need to use the binary or hex representation, also, is missing two characters to by 12-byte or 24-hex.

For example, if your user id is 'my_user_id00', then you can use any of these:

database.test_collection.find_one({'user': ObjectId(b'my_user_id00')})
database.test_collection.find_one({'user': ObjectId('6d795f757365725f69643030')})

You can find more info on the mongoDB API docs.

dsanchez
  • 43
  • 4
0

By default when inserting documents in the collection, if you don't add a field name with the _id in the field name, then MongoDB will automatically add an Object id field as shown below![enter image description here]

(https://i.stack.imgur.com/w6VDQ.png)

So, when performing insert query use _id as like this...

database.test_collection.insert({'_id': 'my_user_id', 'value': 'my_value'})

If you want to ensure that MongoDB does not create the _id Field when the collection is created and if you want to specify your own id as the _id of the collection, then you need to explicitly define this while creating the collection..

Developer
  • 3,309
  • 2
  • 19
  • 23