Adding Object in Array PyMongo

对着背影说爱祢 提交于 2021-01-29 05:19:09

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!