简体   繁体   English

mongodb:如何使用 python (pymongo) 创建计算字段?

[英]mongodb: how to create a calculated field using python (pymongo)?

Is there a way to create a calculated field in mongodb using pymongo?有没有办法使用 pymongo 在 mongodb 中创建计算字段?

example = {
    "field1": 1,
    "field2": 2,
    "calculated_field": "field1" + "field2"
}

The calculated field must always keep the formula, if "field1" will later be modified, the result must update.计算字段必须始终保留公式,如果“field1”稍后将被修改,则结果必须更新。

I have read mongodb documentation and I can see it can be done with aggregation pipeline but pymongo's documentation is not really clear on this procedure.我已经阅读了 mongodb 文档,我可以看到它可以通过聚合管道来完成,但是 pymongo 的文档在这个过程中并不是很清楚。

Edit:编辑:

I am trying, at the moment, to insert a new field as below but the field is not added.目前,我正在尝试插入一个新字段,如下所示,但未添加该字段。

    pipeline = [
    {
        "$addFields": {
            "calculated_field": {"$sum": ["field1", "field2"]}
        }
    }
]

dbCollection = database["col"]

dbCollection.aggregate(pipeline)

You have a couple of different options based on what your goals are.根据您的目标,您有几个不同的选择。

  1. You can use the aggregation pipeline to calculate the sum:您可以使用聚合管道来计算总和:

     [ { '$addFields': { 'total': { '$sum': [ '$field1', '$field2' ] } } } ]

    The result will be a document that has the total field.结果将是一个包含总计字段的文档。 Keep in mind that this will not store the total in your database.请记住,这不会将总数存储在您的数据库中。

     { field1: 5, field2: 3, total: 8, }
  2. You could create a Change Stream to monitor field1 and field2 to check for changes.您可以创建一个 Change Stream 来监控 field1 和 field2 以检查更改。 When changes are made, you could automatically update the total that is stored in your database.进行更改后,您可以自动更新存储在数据库中的总数。 See https://developer.mongodb.com/quickstart/python-change-streams for more information on how to create Change Streams in Python.有关如何在 Python 中创建更改流的更多信息,请参阅https://developer.mongodb.com/quickstart/python-change-streams

  3. If your database is stored in MongoDB Atlas (MongoDB's fully managed database-as-a-service), you can use a Trigger to monitor field1 and field2 for changes.如果您的数据库存储在MongoDB Atlas (MongoDB 的完全托管的数据库即服务)中,您可以使用触发器来监视 field1 和 field2 的更改。 Triggers are built on the same concepts as Change Streams.触发器建立在与变更流相同的概念之上。 Triggers are a bit simpler since you don't have worry about hosting and managing the Change Stream yourself.触发器稍微简单一些,因为您不必担心自己托管和管理 Change Stream。 See https://docs.atlas.mongodb.com/triggers/ for more information on Triggers.有关触发器的更多信息,请参阅https://docs.atlas.mongodb.com/triggers/

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

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