Search code examples
pythonpymongo

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:

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)