📜  mongodb $addToSet (1)

📅  最后修改于: 2023-12-03 14:44:21.241000             🧑  作者: Mango

MongoDB $addToSet

$addToSet is a MongoDB operator used to add a value to an array only if the value is not already present in the array. This operator is particularly useful when dealing with arrays of unique values, such as tags or usernames.

The syntax of $addToSet is as follows:

db.collection.updateOne({ /* query */}, { $addToSet: { /* field: value */ } })

Here, db.collection.updateOne() is the method used to update a single document in a MongoDB collection. The $addToSet operator is used to add a value to a specific field in the document. The query parameter is used to specify which document to update, while the field: value parameter pair specifies which field to update with the new value.

Example

Suppose we have a users collection with the following document:

{
  _id: ObjectId("60f6cf81f992c0b0b8530336"),
  username: "jdoe",
  tags: ["mongodb", "javascript"]
}

To add the tag "nodejs" to the tags array for the document with the _id of 60f6cf81f992c0b0b8530336, we would use the following code:

db.users.updateOne({_id: ObjectId("60f6cf81f992c0b0b8530336")}, {$addToSet: {tags: "nodejs"}})

This will add "nodejs" to the tags array only if it is not already present.

Conclusion

In summary, $addToSet is a MongoDB operator used to add a value to an array only if the value is not already present in the array. This is particularly useful when dealing with arrays of unique values.