从具有嵌套数组元素选择的常规更新中使用聚合管道更新MongoDb 4.2

时间:2020-06-25 20:49:04

标签: python mongodb mongodb-query python-3.8

我尝试用聚合管道编写更新,但是我不知道该怎么做(除了这个简单的更新,我需要条件更新-我只是一个例子)。我尝试了多种变体,但仍然无法正常工作。我要更新的元素是与'judge_id'相匹配的嵌套数组的元素。

如何使用管道语法进行此更新(我需要进行条件更新)?

position.update_one(
    filter={'position': 1,
            'scores.judge_id': 1},
    update={'$set': {'scores.$.evaluation': 10}},
)

我从经典更新中得到了这样的结果:

# original data -> it is O.K. always :)
{'position': 1, 'scores': [{'judge_id': 1, 'evaluation': 1}, {'judge_id': 2, 'evaluation': 2}]}

# it is classic update with use $ operator -> it is O.K. judge_id==1 updated!
{'position': 1, 'scores': [{'judge_id': 1, 'evaluation': 10}, {'judge_id': 2, 'evaluation': 2}]}

但是随着聚合管道的更新-我无法实现同样的目标。

# now I trying pipeline update #1 -> INVALID both evaluation is updated not judge_id==1
# how to select only one element!
{'position': 1, 'scores': [{'judge_id': 1, 'evaluation': 10}, {'judge_id': 2, 'evaluation': 10}]}

# now I trying pipeline update #2 -> INVALID strange results both updated again with full tables.
# if/then/else not works like I think
{'_id': ObjectId('5ef4f432f342e09a163bc921'), 'position': 1, 'scores': [{'judge_id': 1, 'evaluation': [10, 10]}, {'judge_id': 2, 'evaluation': [10, 10]}], 'score': {'0': {'evaluation': 10}}}

这里是完整的代码和数据。

import pymongo

client = pymongo.MongoClient()
client.drop_database('delete_it')
db = client.delete_it
db.position.create_index('position', unique=True)

position: pymongo.collection.Collection = db.position
position.insert_one(
    document={'position': 1,
              'scores': [{'judge_id': 1, 'evaluation': 1},
                         {'judge_id': 2, 'evaluation': 2}]}
)

r = position.find_one(
    filter={'position': 1},
    projection={'_id': False}
)

print(r)

position.update_one(
    filter={'position': 1,
            'scores.judge_id': 1},
    update={'$set': {'scores.$.evaluation': 10}},
)

r = position.find_one(
    filter={'position': 1},
    projection={'_id': False}
)

print(r)


position.update_one(
    filter={'position': 1,
            'scores.judge_id': 1},
    update=[{'$set': {'scores.evaluation': 10}}],
)

r = position.find_one(
    filter={'position': 1},
    projection={'_id': False}
)

print(r)

# conditional update
position.update_one(
    filter={'position': 1,
            'scores.judge_id': 1},
    update=[
        {'$set': {'scores.evaluation': {'$cond': {
            'if': {'$eq': ['$scores.judge_id', 1]},
            'then': 10,
            'else': '$scores.evaluation'
        }}}}
    ],

)

r = position.find_one(
    filter={'position': 1},
    projection={'_id': False}
)

print(r)


我首先找到了这个解决方案。它比concatArrays慢一点。

    position.update_one(
        filter={'position': 1,
                'scores.judge_id': 1},
        update=[
            {
                '$set': {
                    'scores': {
                        '$map': {
                            'input': '$scores',
                            'in': {
                                '$mergeObjects': [
                                    '$$this', {
                                        'evaluation': {
                                            '$cond': {
                                                'if': {'$eq': ['$$this.judge_id', 1]},
                                                'then': NEW_EVALUATION,
                                                'else': '$$this.evaluation'
                                            }
                                        }
                                    }
                                ]
                            }
                        }
                    }
                }
            }
        ],
    )

我找到了第二个解决方案,它更快。

    position.update_one(
        filter={'position': 1,
                'scores.judge_id': 1},
        update=[
            {
                '$set': {
                    'scores': {
                        '$concatArrays': [
                            {
                                # change evaluation of one element
                                '$map': {
                                    # array with one element only matching
                                    'input': {
                                        '$filter': {
                                            'input': '$scores',
                                            'cond': {'$eq': ['$$this.judge_id', 1]}
                                        }
                                    },
                                    'in': {
                                        '$mergeObjects' : [
                                            '$$this', {'evaluation': 10}
                                        ]
                                    }
                                }
                            },
                            # array of rest elements not matching
                            {
                                '$filter': {
                                    'input': '$scores',
                                    'cond': {'$ne': ['$$this.judge_id', 1]}
                                }
                            }
                        ]
                    }
                }
            }
        ],
    )

2 个答案:

答案 0 :(得分:1)

聚合管道不支持位置更新语法。

有人告诉我另一种类似的方法是使用$concatArrays,但是我没有研究这种方法的确切细节。

答案 1 :(得分:-1)

创建聚集不是为了更改数据,而只是为了接收。您可以使用聚合以所需的形式(例如,满足或不满足您的条件的文档标识符数组)创建数据快照,然后使用forEach运算符或您语言所用的另一个迭代器对其进行处理。我不熟悉python,但这是一个javascript示例。

好吧,这就是您想要的。但这不是正确的方法,它也使开发变得复杂。如果您在scores数组中的对象包含一个标识符,则将大大简化该过程。否则,必须直接在管道中处理字段名称的替换。最重要的是,您必须首先将数组扩展为一个对象,然后对其进行更改并将其返回到其原始状态。

db.getCollection("test").aggregate(
// Pipeline
[
    // Stage 1
    {
        "$match": {
            "scores.judge_id":1
        }
    },
    // Stage 2 (convert array to object)
    {
        "$project":{
            "_id": "$_id",
            "position": "$position",
            "scores": {
                "$arrayToObject": {
                    "$reduce":{
                        "input": "$scores",
                        "initialValue": [],
                        "in": {
                            "$concatArrays": [
                                "$$value",
                                [{
                                    "k": {
                                        "$toString": "$$this.judge_id"
                                    }, 
                                    "v": "$$this.evaluation"
                                }]
                            ]
                        }
                    }
                }
            }
        }
    },
    // Stage 3 (update evaluation)
    {
        "$set": {
            "scores.1": 10
        }
    },
    // Stage 4 (convert object to array)
    {
        "$project":{
            "_id": "$_id",
            "position": "$position",
            "scores": {
                "$objectToArray": "$scores"
            }
        }
    },
    // Stage 5 (return the name of the fields)
    {
        "$project":{
            "_id": "$_id",
            "position": "$position",
            "scores": {
                "$reduce":{
                    "input": "$scores",
                    "initialValue": [],
                    "in": {
                        "$concatArrays": [
                            "$$value",
                            [{
                                "judge_id": {
                                    "$toDouble": "$$this.k"
                                }, 
                                "evaluation": "$$this.v"
                            }]
                        ]
                    }
                }
            }
        }
    }
]
);