I am working on a Mongo updateMany() query.
A condensed example of a document in my collection:
{
"CurrentVersion": 3,
"EntryHistory": [
{
"State": 0,
"ProposalPlan": [
{
"Description": "Test",
"State": 1,
"Proposals": [
{
"Subject": "Test",
"Body": "Test",
"Urls": [
{
"Description": "Link text",
"Address": "https://examplelink.com"
}
]
}
]
}
]
}
]
}
Please assume that my test data is just showing structure and not the actual size of the collection and the arrays.
How can I write my updateMany() query to not error out if it encounters a null field in a document? I just want it to continue with updating documents if one is problematic.
Here is the query I wrote:
db.collectionName.updateMany(
{ "ProposalPlan.State": 1 },
{
$set: {
"ProposalPlan.State": 3,
"ProposalPlan.Proposals.10.Urls.0.Address": "https://newlinkexample.com"
}
}
);
My problem is that when I run this query, some documents that meet the filter criteria are “corrupt” and have null or nonexistent Proposals and/or null or nonexistent Urls, so I am faced with an error such as “MongoServerError: Cannot create field ‘0’ in element {Urls: null}”.
I have also tried wrapping the above query in a try catch, as I expected it to continue after a document throws an error, but I see that’s not how it works.
I tried to add to the filters so that I am not even trying to update the corrupt documents to begin with:
db.collectionName.updateMany(
{ "ProposalPlan.State": 1, "ProposalPlan.Proposals.10.Urls.0.Address": { $ne: null } },
{
$set: {
"ProposalPlan.State": 3,
"ProposalPlan.Proposals.10.Urls.0.Address": "https://newlinkexample.com"
}
}
);
But none of this has worked so far. The above extra filter does not throw an error but nothing is updated, and when I try to use the filters with findOne() it just searches infinitely rather than grabbing one of the many records where ProposalPlan.State is 1 and ProposalPlan.Proposals.10.Urls.0.Address is not null.