简体   繁体   中英

Variable inputs into a function in Pymongo

I have multiple lists of dictionaries in Python in the format [dic1, dic2, dic3,..., dicx]

I'm trying to insert these dictionaries as a batch insert in mongodb:

(pseudocode)
db.batch.insert_many(dic1, dic2,...,dicx)

but because each of the arrays are of variable length, I think I need to a for loop, but can't visualize how to do so exactly.

Assuming that the function db.batch.insert() can take a variable number of arguments, you can use the * operator in front of the lists. Consider the simple print function:

>>> words = ["dog","cat","mouse"]
>>> print(*words)
dog cat mouse

print(*words) is thus equivalent to print("dog","cat","mouse")

Presuming you connected to MongoDB and grabbed your database something like this:

import pymongo
from pymongo import MongoClient

client = MongoClient()
db = client.test

Then if your collection is indeed called "batch" you can use the .insert_many() method which accepts an array of dict:

listOfDict = [dict1,dict2,dict3]

db.batch.insert_many(listOfDict)

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