简体   繁体   English

更新命令通过mongo shell运行,但不通过pymongo运行

[英]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. 我正在尝试使用pymongo更新mongo文档中的数组,但是它不起作用,但是将相同的查询复制到robomongo确实可行。 (it returns {'n': 1, 'nModified': 0, 'ok': 1.0, 'updatedExisting': True} ) (它返回{'n': 1, 'nModified': 0, 'ok': 1.0, 'updatedExisting': True}

roboMongo: roboMongo:

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

pymongo code: 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)

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

The {'KEY': '1', 'TYPE': 'my_type'} should be ordered, therefore I force the order by doing: {'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}}}

This way KEY will alway be the first element in the hash and TYPE will be the second one. 这样,KEY将始终是哈希中的第一个元素,而TYPE将是第二个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM