使用 pymongo 将数组插入 mongodb [英] insert array into mongodb using pymongo

查看:46
本文介绍了使用 pymongo 将数组插入 mongodb的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 pymongo 将数组添加到 mongdb

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)我想不出任何其他方法来做到这一点,所以我将它们转换为字符串并连接并尝试将它们添加到帖子中(一定有更好的方法吗?)

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)当我这样做时,我得到的不是欲望影响

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)

推荐答案

首先,将您构造字符串的方式从 tGenerator 方法更改为以下方法:

First, change how you are constructing the string from tGenerator method to below:

returnString += str(i+1) + " " + stringToStuff + ","

其次,您可以使用 split 方法来完成所需的操作,因此您的插入将如下所示:

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)

希望以上对你有用.

这篇关于使用 pymongo 将数组插入 mongodb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆