简体   繁体   中英

insert array into mongodb using pymongo

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)

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.

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