Filipe Santos
Filipe Santos

Reputation: 401

How to insert data inside Mongo object through Python

Inside the expenses collection I have this Json:

{
"_id" : ObjectId("5ad0870d2602ff20497b71b8"),
"Hotel" : {}
}

I want to insert a document or another object if possible inside Hotel using Python.

My Python code:

from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client['db']
collection_expenses = db ['expenses']
#insert
d = int(input('Insert how many days did you stay?: '))
founded_expenses = collection_expenses.insert_one({'days':d})

The code above inserts the document inside the collection. What should I change to add the days inside de Hotel object? Thanks in advance.

Upvotes: 1

Views: 103

Answers (1)

Alexis Facques
Alexis Facques

Reputation: 1873

Instead of using insert_one, you may want to take a look to the save method, which is a little bit more permissive.

Admitting your document is already created in the collection:

[...]
expenses = db['expenses']

# Find your document
expense = expense.find_one({})

expense["Hotel"] = { "days": d }

# This will either update or save as a new document the expense dict,
# depending on whether or not it already has an _id parameter
expenses.save(expense)

Knowing that find_one will return you None if no such document exist, you may want to upsert a document. You can thus easily do so with save.

Upvotes: 1

Related Questions