I have a collection with docs like:
{ID: xxx, firstCreateDate: xxx, isActive: false}
- I want to find all the docs where
isActive = false
, then updateisActive
to true, and also updatefirstCreateDate
to current date if not set before. I’m not sure how to conditionally update filed firstCreateDate. Couldn’t get the conditionally update working right now. Got
firstCreateDate = {$cond:[{"firstCreateDate":{"$exists":false}}, "$firstCreateDate", newdata]}
- I also want to use a custom function to generate a new field internalID based on original
ID
field. I tried to useUpdateMany()
, but seems like there is no way to get the value and calculate the new value using your own function. I’m thinking about useFind()
to find all docs, then decode it, and then update docs one by one based on id. Is there any better solution for this?
This is what I have now:
filter := bson.M{"isActive": false}
update := bson.M{"set": bson.M{"isActive": true, "firstCreateDate": bson.M{
"$cond": bson.A{
bson.M{"firstCreateDate", bson.M{"$exists", false}},
"$firstCreateDate",
newDate,
}
}}}
collection.UpdateByID(
context.Background(),
id,
update,
)
I’m using mongo-driver lib, anyone can help
2
Answers
A few things..
$set
takes mostly the same syntax as the projection operator.Here is the updateMany that will solve your first question. It uses the mongosh syntax but you should be able to convert the logic to go.
I can help you with the first part.
First you just want to find where
isActive
is false and wherefirstCreateDate
is not set. If the field exist and is just Null, take a look at https://www.mongodb.com/docs/manual/reference/operator/aggregation/ifNull/