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)
You have a couple of different options based on what your goals are.
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, }
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.