A conditional update in MongoDB can be accomplished using the `updateOne()`, `updateMany()`, or `findOneAndUpdate()` methods combined with certain query criteria and update operators.
Here’s a general example using `updateOne()`:
```
db.collection.updateOne(
{ “field1”: “value1” }, // Query parameter
{
$set: { “field2”: “new_value2” } // Update parameter
},
{
upsert: true // Optional properties
}
)
```
This command will update the first document that matches the query `“field1”: “value1”` and set the `field2` to `“new_value2”`.
If the `upsert` option is set to true, MongoDB will create a new document when no document matches the query criteria.
For an `updateMany()` operation, the syntax is the same, but it updates all documents that match the query:
```
db.collection.updateMany(
{ “field1”: “value1” },
{
$set: { “field2”: “new_value2” }
},
{
upsert: true
}
)
```
The `findOneAndUpdate()` method updates the first document matching the criteria, returning the updated document:
```
db.collection.findOneAndUpdate(
{ “field1”: “value1” },
{
$set: { “field2”: “new_value2” }
},
{
returnNewDocument: true
}
)
```
You can also use conditional update operators like `$inc`, `$mul`, `$rename`, `$unset`, etc. in the update parameter.
For example, here’s how to increment a field’s value conditionally:
```
db.collection.updateOne(
{ “field1”: “value1” },
{
$inc: { “field3”: 10 } // increment `field3` by 10
}
)
```
Remember, you should replace “collection” with your target collection name.