简体   繁体   中英

Pymongo: collection.find_one() returns dictionary object instead of document

I started setting up a MongoDB and communicate with it via Python / Pymongo. But I came across this problem:

code:

my_dict = {"key1": "value1", "key2", "value2"}
my_collection.insert_one(my_dict)
doc = my_collection.find_one({"key1": "value1"})
print(doc)

output:

{'_id': ObjectId('5a5c2c2b44cdc53e8417825e'), 'key1': 'value1', 'key2': 'value2'}

The same happens without arguments. This function is supposed to return a single document, so what's wrong?

Thanks for your answers. Greetings, Nils

The issue in your case is you are inserting single document.

my_dict = {"key1": "value1", "key2", "value2"}

This is a single document. If you want it to be treated as two separate documents. You should try this :

my_dict = [{"key1": "value1"},{"key2", "value2"}]

You can refer the pymongo documentation for more details.

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