问题
I am trying to add array into mongdb using pymongo
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?)
2)When I do this, instead of desire affect, I get
["'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)
回答1:
First, change how you are constructing the string from tGenerator
method to below:
returnString += str(i+1) + " " + stringToStuff + ","
Second, you can use the split
method to do the required, so your insertion will look something like below:
post = {
"name":name2,
"score":8,
"date":datetime.datetime.now(),
"output": tGenerator(createLoop()).split(',')
}
collection2.insert_one(post)
I hope, the above works for you.
来源:https://stackoverflow.com/questions/62034775/insert-array-into-mongodb-using-pymongo