简体   繁体   中英

Insert ObjectId into mongodb

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)?

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 .

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..

As long as your have right string in Objectid, it will work.your user I'd must be byte string obtained from ObjectId(something)._ObjectId_id or simply are hex string. pliz try to show your user_Id if its not confidential

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM