2

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:[email protected]: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)
0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, I missed this.. thank you so much for pointing this out! Huge help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.