【问题标题】:Variable inputs into a function in PymongoPymongo中函数的变量输入
【发布时间】:2015-09-27 06:39:18
【问题描述】:

我在 Python 中有多个字典列表,格式为 [dic1, dic2, dic3,..., dicx]

我正在尝试将这些字典作为批量插入插入到 mongodb 中:

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

但是因为每个数组都是可变长度的,我想我需要一个 for 循环,但无法准确地想象如何做到这一点。

【问题讨论】:

  • batch.insert()是你定义的函数吗?
  • @AnandSKumar 和所有 python 人。他是在 collection 对象上的 .insert() 的实际 pymongo 方法的“伪代码”。 db 也可以这样表达。那么db 是 pymongo 调用方法的数据库。
  • @BlakesSeven 看起来 mongodb 3.0+ 的 pymongo 的批处理方法是 insert_many()。
  • @SLee 是的,就像我当时回答的那样。 .insert() 也是一种方法,但它是单数的。并且普遍接受在最近的驱动程序中替换为.insert_one()

标签: python arrays mongodb for-loop pymongo


【解决方案1】:

假设函数 db.batch.insert() 可以接受可变数量的参数,您可以在列表前面使用 * 运算符。考虑简单的打印功能:

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

print(*words) 因此等价于 print("dog","cat","mouse")

【讨论】:

  • Yead db.batch.insert() 是 pymogo 与 MongoDB 一起使用的真实方法。问题是什么。
【解决方案2】:

假设您连接到 MongoDB 并获取您的数据库,如下所示:

import pymongo
from pymongo import MongoClient

client = MongoClient()
db = client.test

如果你的集合确实被称为“批处理”,你可以使用.insert_many() 方法,它接受一个dict数组:

listOfDict = [dict1,dict2,dict3]

db.batch.insert_many(listOfDict)

【讨论】:

    猜你喜欢
    • 2016-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-09
    • 1970-01-01
    相关资源
    最近更新 更多