pymongo我应该如何指定数据路径?

时间:2018-04-25 02:02:27

标签: python pymongo pymongo-3.x

users    path     common             config             
                  exchange_rate             
                  prod_data             
                  delivery_fee          

         site     shoppingmall       settings    description
                                                 highlight
                                                 prohibit_words

我做了以下但失败了。

db = MongoClient("localhost:99999").users
config_data = get_config()   --> just get config_data (json)
db.path.common.config.insert(config_data)

我想为每个客户这样做。 我该怎么办? (我喜欢这个例子,因为我是初学者......(T.T)) 谢谢!!

1 个答案:

答案 0 :(得分:1)

我认为失败是因为你的数据不是json。如果你想从csv文件插入数据,你可以试试这个:

将pandas导入为pd

from pymongo import MongoClient

import json



def mongoimport(csv_path, db_name, coll_name, db_url='localhost', db_port=27000)

    """ Imports a csv file at path csv_name to a mongo colection

    returns: count of the documants in the new collection

    """

    client = MongoClient(db_url, db_port)

    db = client[db_name]

    coll = db[coll_name]

    data = pd.read_csv(csv_path)

    payload = json.loads(data.to_json(orient='records'))

    coll.remove()

    coll.insert(payload)

    return coll.count()

此代码易于理解,此代码来自https://gist.github.com/jxub/f722e0856ed461bf711684b0960c8458