Introduction to MongoDB $setOnInsert Operator

The $setOnInsert operator in MongoDB is used to update a document only if it does not exist while performing an update operation. This operator is used to specify the values to be set for the fields when a new document is inserted. If the update operation being performed is updating an existing document, then the $setOnInsert operator will not be effective.

Syntax

The syntax of the $setOnInsert operator is as follows:

{ $setOnInsert: { <field1>: <value1>, ... } }

Here, <field1> represents the name of the field to be set, and <value1> represents the value to be set.

Use Cases

The $setOnInsert operator can be used when we need to insert default field values when executing an update operation and the document does not exist. For example, when creating a new user, we may need to add some default values to the new user’s document, such as creation time, last login time, etc. At this point, the $setOnInsert operator can be used to set these default values.

Examples

Example 1

Assume we have a collection named users that stores information about some users. Now, we need to insert a new user information into the collection, which includes four fields: username, email, created_at, and updated_at. When inserting a new document, we need to set the values of the created_at and updated_at fields to the current time. At this point, the $setOnInsert operator can be used to set these default values. The specific implementation code is as follows:

db.users.update(
  { username: "JohnDoe" },
  {
    $setOnInsert: {
      email: "[email protected]",
      created_at: new Date(),
      updated_at: new Date()
    }
  },
  { upsert: true }
)

After executing the above code, if there is no user with the username JohnDoe in the users collection, a new user information containing four fields, email, created_at, and updated_at, will be inserted and the values of created_at and updated_at fields will be set to the current time. If there is a user with the username JohnDoe in the users collection, no operation will be performed.

Example 2

Assume we have a collection named articles that stores information about some articles, which includes the following fields:

{
  "_id": ObjectId("6140b7a123c40bfc5e5ecb02"),
  "title": "Introduction to MongoDB",
  "content": "MongoDB is a document database",
  "created_at": ISODate("2022-09-14T10:23:41.729Z"),
  "updated_at": ISODate("2022-09-14T10:23:41.729Z")
}

Now, we need to insert a new article into the collection, which includes four fields: title, content, published_at, and updated_at. When inserting a new document, we need to set the value of the published_at field to the current time. At this point, the $setOnInsert operator can be used to set these default values.

We can use the following command to insert a new article into the articles collection:

db.articles.updateOne(
  { title: "Introduction to MongoDB" },
  {
    $setOnInsert: {
      content: "This is a new MongoDB article",
      published_at: new Date(),
      updated_at: new Date()
    }
  },
  { upsert: true }
)

This command searches for a document in the articles collection with the title “Introduction to MongoDB”. If the document is found, only its updated_at field is updated. If the document is not found, a new document is created with default values, where the published_at and updated_at fields are set to the current time.

After executing the above command, the documents in the articles collection will look like this:

{
  "_id": ObjectId("6140b7a123c40bfc5e5ecb02"),
  "title": "Introduction to MongoDB",
  "content": "MongoDB is a document database",
  "created_at": ISODate("2022-09-14T10:23:41.729Z"),
  "updated_at": ISODate("2022-09-14T10:23:41.729Z")
},
{
  "_id": ObjectId("622634bfb59b6c2318656ed7"),
  "title": "Introduction to MongoDB",
  "content": "This is a new MongoDB article",
  "published_at": ISODate("2023-03-09T02:54:11.526Z"),
  "updated_at": ISODate("2023-03-09T02:54:11.526Z")
}

As we can see, a new article has been inserted where the published_at and updated_at fields are set to the current time.

Conclusion

The $setOnInsert operator is a very useful operator in MongoDB. It can be used to set default values for fields when inserting documents, reducing the amount of code to be written and improving development efficiency. In actual development, we can use this operator flexibly to meet project requirements based on specific situations.