1

What I'm trying to achieve in here is to update a given set of documents that contain a given set of fields, either one, another or both.

I have two questions actually for this matter...

Can MongoDB process fields that aren't present in the document being processed? Like what I'm trying to achieve here, sum two fields, and if one is null just sum 0.

And the other one is the error that I'm getting in the query...

db.getCollection('my_collection').update({'$or': [{
        'a_field': 1}, {
        'another_field': 1
    }
    ]},
        {'$set': {
            'another_field': {
                '$sum': [
                    '$a_field', '$another_field'
                ]
            }
        },
            '$unset': {'a_field': ''}})

Giving me the following error...

The dollar ($) prefixed field '$sum' in 'another_field.$sum' is not valid for storage.
Lenny D.
  • 288
  • 1
  • 4
  • 14

1 Answers1

0

There is no $sum UPDATE operator in mongodb and hence the error. The one you are confused with is an aggregation operator and can only be used to query data in a fashion. Also, the operator you are looking at is $inc, however you CANNOT update the document in the fashion you are trying to. There is an OPEN ticket for this feature to mongodb. Ticket

Hope this clarifies

See this answer for more on achieving what you are trying to do.

Avij
  • 684
  • 7
  • 17
  • Thanks for the clarification @Avij... What I'm wondering now is if the code from the answer you provided me would work as it is inside PyMongo with a Code object? – Lenny D. Jan 03 '18 at 14:19
  • on which platform driver you want to perform this operation? @LennyD. – Avij Jan 03 '18 at 15:13