[英]Variable inputs into a function in Pymongo
I have multiple lists of dictionaries in Python in the format [dic1, dic2, dic3,..., dicx] 我在Python中有多个字典列表,格式为[dic1,dic2,dic3,...,dicx]
I'm trying to insert these dictionaries as a batch insert in mongodb: 我正在尝试将这些字典作为批处理插入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. 但是因为每个数组的长度都是可变的,所以我认为我需要一个for循环,但是无法直观地看到如何做到这一点。
Assuming that the function db.batch.insert() can take a variable number of arguments, you can use the * operator in front of the lists. 假设函数db.batch.insert()可以接受可变数量的参数,则可以在列表前面使用*运算符。 Consider the simple print function: 考虑简单的打印功能:
>>> words = ["dog","cat","mouse"]
>>> print(*words)
dog cat mouse
print(*words) is thus equivalent to print("dog","cat","mouse") 因此,print(* words)等效于print(“ dog”,“ cat”,“ mouse”)
Presuming you connected to MongoDB and grabbed your database something like this: 假设您已连接到MongoDB并获取了数据库,如下所示:
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: 然后,如果您的集合确实称为“批处理”,则可以使用.insert_many()
方法,该方法接受dict数组:
listOfDict = [dict1,dict2,dict3]
db.batch.insert_many(listOfDict)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.