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

MongoDB: Difference between $set and normal colon assignment update

I will like to know the difference between the two update operations below.

Assuming the collection doc looks like this:

{
    _id: 1,
    name: "Jack",
    books: [
        {_id: "1a", title: "Book 1", rating: 5},
        {_id: "1b", title: "Book 2", rating: 3},
    ]
}

With $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

Customer.updateOne({_id: 1, "books._id": "1a"}, {$set: {"books.$.rating": 2}});

Without $set:

Customer.updateOne({_id: 1, "books._id": "1a"}, {"books.$.rating": 2});

When I test both, they return the same result

 {
    _id: 1,
    name: "Jack",
    books: [
        {_id: "1a", title: "Book 1", rating: 2},
        {_id: "1b", title: "Book 2", rating: 3},
    ]
 }

So, what is the difference between them? and which is better?

>Solution :

Mongoose automatically adds $set. Check the documentation

Where says:

By default, if you don’t include any update operators in update, Mongoose will wrap update in $set for you

So the result is the same because the query is the same.

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