更新命令通过 mongo shell 起作用,但不能通过 pymongo

update commands works via mongo shell but not via pymongo

我正在尝试使用 pymongo 更新 mongo 文档中的数组,但它不起作用,但将相同的查询复制到 robomongo 确实有效。 (它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代码:

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)

文件:

{
    "_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
}

我想这可能与 " 和 ' 有关?

有什么建议吗?

谢谢

应该订购 {'KEY': '1', 'TYPE': 'my_type'},因此我通过以下方式强制订购:

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}}}

这样 KEY 将始终是散列中的第一个元素,TYPE 将是第二个元素。