问题
I am working on a migration function that needs to retrieve soccer game results in certain time intervals and update existing bet documents for those games in MongoDB.This code will be called multiple times throughout the day and I'm looking for an optimized solution regarding the computation performance
The data structure looks like this.
{
"games": {
"2324754": {
"id": "2324754",
"comp_id": "1005",
"formatted_date": "14.03.2018",
"localteam_name": "Barcelona",
"localteam_score": "3",
"visitorteam_name": "Chelsea",
"visitorteam_score": "0"
},
"2324756": {
"id": "2324756",
"comp_id": "1005",
"formatted_date": "14.03.2018",
"localteam_name": "Beşiktaş",
"localteam_score": "1",
"visitorteam_name": "Bayern München",
"visitorteam_score": "3",
}
},
"bets": [
{
"_id": "5aa9535c6c4f437de713452a",
"match_id": "2324756"
},
{
"_id": "5aacf9605c41bc0b3db304fd",
"match_id": "2324754"
}
]
}
One option is iterating the bets array and calling findOneAndUpdate()
on individual bet documents.Due to performance issues that would not work very well for bets array with a count of 150-200 elements.
The question is would it be possible to achieve this migration with updateMany()
operation.
It would not be a problem to query all documents with the given match_id
but how would one build a set condition for updateMany()
?
Given examples in the documentation assumes that desired fields of multiple documents are updated with same values. https://docs.mongodb.com/manual/reference/method/db.collection.updateMany/
UPDATE:
Another option is creating a Bulk operation and doing findOneAnUpdate()
inside the for loop.But once again I'm not sure if that would be performant enough. Can anyone confirm that this would be the best/only option for his?At least that would not load the mongo server with multiple update requests.
https://docs.mongodb.com/manual/reference/method/Bulk.find.update/
var bulk = db.items.initializeUnorderedBulkOp();
//Iterate Bets
//findOneAnUpdate
bulk.execute();
来源:https://stackoverflow.com/questions/49335895/mongodb-updatemany-with-different-set-objects