Barani Myat Tun
Barani Myat Tun

Reputation: 109

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. Here, I inserted a document to MongoDB by using insert_one(). My question is how can I store that data in a variable and use the variable in the insert_one() method? For.eg, db.restaurants.insert_one(somthng) where somthng is the variable that will be storing the document.

Upvotes: 0

Views: 4163

Answers (1)

jyap
jyap

Reputation: 1584

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)

Upvotes: 2

Related Questions