Search⌘ K
AI Features

Solution: Updating Arrays

The solution for updating arrays in MongoDB involves using the `updateMany` command to modify multiple documents in the products collection based on specific conditions, such as price being less than or equal to zero. The `$set` operator is employed to assign new values to fields, while `$addToSet` ensures that unique values are added to an array, preventing duplicates. This method effectively marks products as inactive and flags them for review, demonstrating the use of comparison operators and update operations in MongoDB.

We'll cover the following...
Query
db.products.updateMany(
{ price: { $lte: 0 } },
{
$set: {
price: 49,
status: "Inactive"
},
$addToSet: {
tags: "needs-review"
}
}
)
, db.products.find({status: "Inactive"})

Explanation

The explanation of the query is given below:

  • Line 1: db.products.updateMany; this command tells MongoDB ...