JMJ
JMJ

Reputation: 571

How to access Pymongo nested document with variable

I understand that in order to find a nested document that I am to use the dot notation, but I need what follows the dot be in variable form. I am doing the following:

collection.update_one(
                    {'_id': md5_hash}, 
                    {'$addToSet' : {
                     'src_id': src_id,
                     'offset.src_id' : offset}}
                                  )

and getting

{
        "_id" : "de03fe65a6765caa8c91343acc62cffc",
        "total_count" : 1,
        "src_id" : [
                "a3c1b98d5606be7c5f0c5d14ffb0b741"
        ],
        "offset" : {
                "a3c1b98d5606be7c5f0c5d14ffb0b741" : [
                        512
                ],
                "src_id" : [
                        512,
                        1024,
                        1536,
                        2048,
                        2560,
                        3072,
                        3584,
                        4096,
                        4608
                ]
        },
        "per_source_count" : {
                "a3c1b98d5606be7c5f0c5d14ffb0b741" : 1
        }
}

I don't want "src_id" in the offset document I want to add to the a3c1b98d5606be7c5f0c5d14ffb0b741 key. I am using python3.5 and pymongo version 3.2.2. Thanks!

Upvotes: 2

Views: 219

Answers (1)

alecxe
alecxe

Reputation: 473873

You can just have a nested dictionary:

collection.update_one({'_id': md5_hash}, 
                      {'$addToSet': {'offset': {src_id: offset}}})

Or, you can dynamically make the field via string formatting or concatenation:

collection.update_one({'_id': md5_hash}, 
                      {'$addToSet': {'offset.%s' % src_id: offset}})

Upvotes: 2

Related Questions