Reputation: 31
My collection:
{"date": "5-1-2020", "country": "US", score: 0}
{"date": "5-1-2020", "country": "CA", score: 10}
{"date": "5-2-2020", "country": "US", score: 7}
{"date": "5-2-2020", "country": "CA", score: 11}
Here is the scenario: I need to update the score for the US game on 5-1-2020 to 17.
Pseudocode:
Search for date: "5-1-2020" and country "US".
If found UPDATE score to 17.
If not found insert record of {"date": "5-1-2020", "country": "US", score: 17}
My working solution:
FOR doc in collection
UPSERT { "date": "5-1-2020", "country": "US" }
INSERT doc
UPDATE { "score": 17 } in collection
If my collection was:
{"date": "5-1-2020", "country": "CA", score: 10}
{"date": "5-2-2020", "country": "US", score: 7}
{"date": "5-2-2020", "country": "CA", score: 11}
The solution/upsert doesn't work.
Upvotes: 0
Views: 112
Reputation: 11885
I think what you mean to do is this:
UPSERT { "date": "5-1-2020", "country": "US" }
INSERT { "date": "5-1-2020", "country": "US", "score": 17 }
UPDATE { "score": 17 } IN collection
Find document based on date and country and update its score, or insert a new document with date, country and score. Note that there is no outer FOR loop, which would iterate over the collection unnecessarily and potentially cause the same update to be performed hundred of times.
Upvotes: 1