简体   繁体   English

用pymongo更新为Mongo文档中的平均值

[英]Update to average value in Mongo document with pymongo

I want to update field in exists mongodb document. 我想更新存在的mongodb文档中的字段。 But set value should be average value of old value and new value. 但设定值应为旧值和新值的平均值。

I can get old value from mongodb document and calculate average value, and set into field, but it's not thread safety and old value in mongodb document might change while I calculate average. 我可以从mongodb文档中获取旧值并计算平均值,然后设置为字段,但它不是线程安全性,因此在计算平均值时,mongodb文档中的旧值可能会更改。

Example, document: 示例文件:

{ '_id': ObjectId("55d49338b9796c337c894df3"), value: 10 } {'_id':ObjectId(“ 55d49338b9796c337c894df3”),值:10}

Python code: Python代码:

# new_value = 15, therefore average_value = 12.5
db.mycollection.update_one(
    {'_id': '55d49338b9796c337c894df3'},
    {...} <- What there?
)

Before: 之前:

{ '_id': ObjectId("55d49338b9796c337c894df3"), value: 12.5 } {'_id':ObjectId(“ 55d49338b9796c337c894df3”),值:12.5}

You can use the aggregation framework to do update. 您可以使用聚合框架进行更新。 The pipeline steps you need for this are $addFields and $out . 为此所需的管道步骤是$addFields$out The $addFields operator allows you to replace an existing fields within the collection with results from an expression, which would involve the arithmetic operator $avg to compute the average. $addFields运算符使您可以用表达式的结果替换集合中的现有字段,该表达式将涉及算术运算符$avg以计算平均值。

The $avg operator, if used in the $project (or $addFields ) stage, can accept a list of expressions and with that list you can push values from the existing field and the new value for computing the average of these two. $avg运算符(如果在$project (或$addFields )阶段中使用)可以接受表达式列表,使用该列表,您可以从现有字段中推入值,并推入新值以计算这两个值的平均值。

The $out operator as the final stage will update the existing collection as it writes the resulting documents of the aggregation pipeline to a collection. 作为最后阶段的$out运算符将更新现有集合,因为它将聚合管道的结果文档写入到集合中。

The following example describes the above update operation disguised as an aggregate operation: 以下示例描述了伪装成聚合操作的上述更新操作:

new_value = 15
db.mycollection.aggregate([
    { "$addFields": {
        "value": { "$avg":  ["$value", new_value] }
    } },
    { "$out": "mycollection" }
])

or with MongoDB 3.2 using $project as 或在MongoDB 3.2中使用$project作为

new_value = 15
db.mycollection.aggregate([
    { "$project": {
        "value": { "$avg":  ["$value", new_value] }
    } },
    { "$out": "mycollection" }
])

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

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