Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is $set in MongoDB?

I am coding along with some MongoDB tutorial. I came across this.

const updatedUser = await User.findByIdAndUpdate(
      req.params.id,
      {
        $set: req.body,
      },
      { new: true }
    );

What exactly is $set? I think it is used to set anything from req.body to the DB, but I want to see some documentation about it and other $ use cases. However, I cannot find any documentation about $set.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The $set operator replaces the value of a field with the specified value.

This means that when u update some data, u can set the values of specific fields, even if those fields do not exist yet.

Here is all information u need: https://docs.mongodb.com/manual/reference/operator/update/set/

"If the field does not exist, $set will add a new field with the
specified value, provided that the new field does not violate a type
constraint. If you specify a dotted path for a non-existent field,
$set will create the embedded documents as needed to fulfill the
dotted path to the field."

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading