简体   繁体   English

插入mongoDB时,使用python将json数据存储到变量中

[英]Storing json data into a variable using python when inserting into mongoDB

from pymongo import MongoClient

client = MongoClient()
db = client.test
coll = db.dataset

from datetime import datetime
result = db.restaurants.insert_one(
    {
        "address": {
            "street": "2 Avenue", 
            "zipcode": "10075",
            "building": "1480",
            "coord": [-73.9557413,40.7720266]
        },
        "borough": "Manhattan", 
        "cuisine": "Italian", 
        "grades": [
            {
                "date": datetime.strptime("2014-10-01", "%Y-%m-%d"),
                "grade": "A", 
                "score": 11
            },
            {
                "date": datetime.strptime("2014-01-16", "%Y-%m-%d"),
                "grade": "B", 
                "scroe": 17
            }

        ],
        "name": "Vella", 
        "restaurant_id": "41704620"
    }
 )

result.inserted_id

I have a python code mentioned above. 我有上面提到的python代码。 Here, I inserted a document to MongoDB by using insert_one(). 在这里,我使用insert_one()将文档插入到MongoDB中。 My question is how can I store that data in a variable and use the variable in the insert_one() method? 我的问题是如何将数据存储在变量中,并在insert_one()方法中使用该变量? For.eg, db.restaurants.insert_one(somthng) where somthng is the variable that will be storing the document. 例如,db.restaurants.insert_one(somthng),其中somthng是将用于存储文档的变量。

Is this what you mean? 你是这个意思吗?

something = {
        "address": {
            "street": "2 Avenue", 
            "zipcode": "10075",
            "building": "1480",
            "coord": [-73.9557413,40.7720266]
        },
        "borough": "Manhattan", 
        "cuisine": "Italian", 
        "grades": [
            {
                "date": datetime.strptime("2014-10-01", "%Y-%m-%d"),
                "grade": "A", 
                "score": 11
            },
            {
                "date": datetime.strptime("2014-01-16", "%Y-%m-%d"),
                "grade": "B", 
                "scroe": 17
            }

        ],
        "name": "Vella", 
        "restaurant_id": "41704620"
    }

result = db.restaurants.insert_one(something)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM