Shai M.
Shai M.

Reputation: 1314

update commands works via mongo shell but not via pymongo

I'm trying to update an array inside a mongo document by using pymongo but it is not working, but copy same query to robomongo does works. (it returns {'n': 1, 'nModified': 0, 'ok': 1.0, 'updatedExisting': True})

roboMongo:

db.my_collection.updateMany(
    {'start_time': 1501700400.0},
    {'$pull': {'related': {'$in': [{'KEY': '1', 'TYPE': 'my_type'}]}}},
    {upsert:true}
)

pymongo code:

query_document = {'start_time': 1501700400.0}
update_command = {'$pull': {'related': {'$in': [{'KEY': '1', 'TYPE': 'my_type'}]}}}
_client[db][collection].update_many(query_document, update_command, True)

document:

{
    "_id" : ObjectId("598570c4ffd387293e368c8d"),
    "related" : [ 
        {
            "KEY" : "6",
            "TYPE" : "my_type"
        }, 
        {
            "KEY" : "2",
            "TYPE" : "my_type"
        }, 
        {
            "KEY" : "3",
            "TYPE" : "my_type"
        }, 
        {
            "KEY" : "5",
            "TYPE" : "my_type"
        }, 
        {
            "KEY" : "8",
            "TYPE" : "my_type"
        }
    ],
    "end_time" : 1501621200.0,
    "start_time" : 1501700400.0
}

I'm thinking maybe it is related to " and ' ?

any advice?

Thanks

Upvotes: 0

Views: 225

Answers (1)

Shai M.
Shai M.

Reputation: 1314

The {'KEY': '1', 'TYPE': 'my_type'} should be ordered, therefore I force the order by doing:

ordered_relateds = []
for ptr in ptrs_to_remove:
    ordered_ptrs.append(collections.OrderedDict(sorted(related.items(), key=lambda t: t[0])))

update_command = {"$pull": {"related": {"$in": ordered_related}}}

This way KEY will alway be the first element in the hash and TYPE will be the second one.

Upvotes: 1

Related Questions