问题
How do I achieve a structure like following in Python?
Help appreciated!
回答1:
Here's an example to demonstrate $push
:
from pymongo import MongoClient
client = MongoClient()
db = client.test_db
movies = db.movies
inserted_id = movies.insert_one({
'name': 'Movie 1',
'reviews': []
}).inserted_id
movies.update_one({'_id': inserted_id}, {
'$push': {
'reviews': [
{
'listing_id': '1',
'reviewer_id': 'r1'
}
]
}
})
Output from mongo console:
> db.movies.findOne()
{
"_id" : ObjectId("5ef0fb38642f75302be0c3f6"),
"name" : "Movie 1",
"reviews" : [
[
{
"listing_id" : "1",
"reviewer_id" : "r1"
}
]
]
}
来源:https://stackoverflow.com/questions/62521069/adding-object-in-array-pymongo