Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pymongo is it possible to insert one with insert_many?

This may sound like a dumb question but I was working with pymongo and wrote the following function to insert documents and was wondering if the insert_many method would also work for one record inserts, that way I wouldn’t need another function in case I was just inserting one record.

This is my function:

def insert_records(list_of_documents: list, collection):
    i = collection.insert_many(list_of_documents)
    print(len(i.inserted_ids), " documents inserted!")

When I insert one it throws an error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

post1 = {"_id":0, "user_name":"Jack"}
insert_records(list(post1), stackoverflow)

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

I know I can use insert_one() for this purpose, I was just wondering if it was possible to do everything with insert_many(), as the original insert() method is deprecated. Thanks!

>Solution :

As your post1 is a dict when you use list(post1) you have a list of keys:

>>> list(post1)
['_id', 'user_name']

Use instead:

>>> [post1]
[{'_id': 0, 'user_name': 'Jack'}]

So:

insert_records([post1], stackoverflow)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading