Introduction to MongoDB $addToSet Operator
The Mongodb $addToSet
operator is used to add elements to an array field in a Mongodb document, but only if the element does not already exist in the array. It is an operator in the Mongodb query language and can be combined with other operators to construct more complex query statements.
Syntax
The syntax of the $addToSet
operator is as follows:
{ $addToSet: { <field>: <value> } }
Here, <field>
is the array field to which the element is to be added, and <value>
is the element value to be added.
Usage
The $addToSet
operator is typically used to add elements to an array field in a document, but only if the element does not already exist in the array. For example:
- Add new favorites to a user document’s favorites array field.
- Add new tags to an article document’s tags array field.
Example
Assume we have a collection named users
that stores user names and their favorite items. The favorite items are an array that stores the names of the items that the user likes. We want to add some new favorite items, but only add those that do not already exist in the favorites array. This can be achieved using the $addToSet
operator:
db.users.update(
{ name: "Alice" },
{ $addToSet: { favorites: { $each: ["Item A", "Item C", "Item D"] } } }
)
The above query will add three new items: Item A, Item C, and Item D to the favorites of Alice. If Item A already exists in the favorites array, it will not be added again. We use the $each
operator to add multiple elements at once, instead of calling the $addToSet
operator multiple times.
Suppose the following document exists in the collection:
{ "name": "Alice", "favorites": ["Item A", "Item B", "Item E"] }
After executing the above query, the document will become:
{ "name": "Alice", "favorites": ["Item A", "Item B", "Item E", "Item C", "Item D"] }
Conclusion
The $addToSet
operator is a commonly used operator in the Mongodb query language that can be used to add elements to an array field, but only if the element does not already exist in the array. It can be combined with other operators to construct more complex query statements.