Home > Software design >  MongoDB: Difference between $set and normal colon assignment update
MongoDB: Difference between $set and normal colon assignment update

Time:02-06

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:

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?

CodePudding user response:

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.

  •  Tags:  
  • Related