[英]insert array into mongodb using pymongo
I am trying to add array into mongdb using pymongo我正在尝试使用 pymongo 将数组添加到 mongdb
I have another program that will return something like我有另一个程序会返回类似
['1 aksdfjas;dkfjsa;dfkj','2 ;alksdjf;askdjf;asdfjkasdf', '3 ;alksdfj;asdlkfj;asdfj']
and I want to add them into the insert.我想将它们添加到插入中。
1)I cannot think of any other ways to do it so I am converting them to string and concatenate and trying to add them to the post(there must be better way no?) 1)我想不出任何其他方法来做到这一点,所以我将它们转换为字符串并连接并尝试将它们添加到帖子中(必须有更好的方法不是吗?)
2)When I do this, instead of desire affect, I get 2)当我这样做时,我得到的不是欲望影响
["'1 aksdfjas;dkfjsa;dfkj','2 ;alksdjf;askdjf;asdfjkasdf', '3 ;alksdfj;asdlkfj;asdfj'",]
That extra quotes.. how can I correct this?额外的引号..我该如何纠正这个?
import pymongo
import time
import datetime
from random import *
from pymongo import MongoClient
client = MongoClient('mongodb://user:abc123@10.0.0.1:27017')
stringToStuff = 'blabh blah blahhhhh'
def createLoop():
return randint(5,15)
def tGenerator(e):
returnString = ''
for i in range(e):
returnString += "'" + str(i+1) + " " + stringToStuff + "',"
return returnString
db = client['pytest']
collection = db['test']
names = db.test.find()
collection2 = db['pytestResult']
for p in names:
print(p['name'])
name2 = p['name']
#post = {"name":name2,"score":8,"date":datetime.datetime.now()}
post = {
"name":name2,
"score":8,
"date":datetime.datetime.now(),
#”output”: ['1 aksdfjas;dkfjsa;dfkj','2 ;alksdjf;askdjf;asdfjkasdf', '3 ;alksdfj;asdlkfj;asdfj',]
“output”: [tGenerator(createLoop())]
}
collection2.insert_one(post)
First, change how you are constructing the string from tGenerator
method to below:首先,将构建字符串的方式从
tGenerator
方法更改为以下:
returnString += str(i+1) + " " + stringToStuff + ","
Second, you can use the split
method to do the required, so your insertion will look something like below:其次,您可以使用
split
方法来执行所需的操作,因此您的插入将如下所示:
post = {
"name":name2,
"score":8,
"date":datetime.datetime.now(),
"output": tGenerator(createLoop()).split(',')
}
collection2.insert_one(post)
I hope, the above works for you.我希望,以上内容对你有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.