I'm writing data to MongoDB using pymongo.

I receive this error when performing the write operation.

TypeError: document must be an instance of dict, bson.son.SON, or other type  that inherits from collections.MutableMapping

If I print the data, and copy it with an insert_one() call, the information is written with the shell. I've tried converting the variable to a str, but I am not sure how it is formatted incorrectly, as if I copy the print line and perform the operation, it is added. This leads to me to suspect that there was not a problem with the format of the JSON object, but it's encoding or some variant thereof, or small syntax of the returned JSON object.

post_id = post_db.insert_one(chunk).inserted_id
2

There are 2 answers

0
otayeby On

I had the same TypeError, when I used .insert_one() to insert many objects at the same time. Use bulk insert (.insert_many()), as recommended by the tutorial at: http://api.mongodb.org/python/current/tutorial.html#bulk-inserts.

1
Bedi Egilmez On

I had the same error since I was passing a tuple to the insert_one() function. Double check the datatype you are passing into this function, as error explicitly says there are some datatypes are accepted to pass into this.

type(chunk) will be helpful for you.