0

Is there a way to create a calculated field in mongodb using pymongo?

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.

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.

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)
3
  • can you post the aggregation example you have used Commented Aug 3, 2020 at 10:36
  • I have tried like in the edit and other examples from pymongo documentation but nothing seems to work. I'm a little lost and I think I'm missing something. Commented Aug 3, 2020 at 11:02
  • try to search for mongodb middleware Commented Aug 3, 2020 at 11:25

1 Answer 1

1

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

  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. 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. See https://docs.atlas.mongodb.com/triggers/ for more information on Triggers.

Sign up to request clarification or add additional context in comments.

3 Comments

I have tried the exact pipeline you described but the field is not added. From python I have tried both "dbCollection.aggregate(pipeline)" and "database.command('aggregate', "collection", pipeline=pipeline, explain=True)".
anyway.. I have used another approach but thank you for the help and good read!
Glad you were able to get it working! To clarify further - the aggregation pipeline does not save the results to the database unless you add a stage to specifically do so like $out (docs.mongodb.com/manual/reference/operator/aggregation/out). If you don't use $out, the results of the pipeline will be returned to you so you can see them and work with them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.