WalzoneInterview Prep
πŸ“ž Interviewing soon? Practice with a realistic AI mock phone interview β€” it calls you, then scores you. First 15 min FREE β†’

MongoDB Β· Intermediate Β· question 33 of 100

Explain the difference between the $push and $addToSet update operators.?

πŸ“• Buy this interview preparation book: 100 MongoDB questions & answers β€” PDF + EPUB for $5

Both $push and $addToSet are update operators in MongoDB which are used to add new elements to an array field. However, the key difference between these two update operators is how they handle inserting new elements into an array field.

The $push operator adds a specified value to an array field, even if it already exists in the array. If the specified value is an array itself, $push inserts the entire array as a single element of the main array. The syntax for using $push is as follows:

db.collection.update(
   <query>,
   { $push: { <field>: <value> } },
   { <options> }
)

Here, β€˜<field>β€˜ is the array field to which the value is being pushed and β€˜<value>β€˜ is the value being pushed. For example, consider the following query:

db.myCollection.update({"_id": ObjectId("5ea1ad2e284b54a77bcc97a4")}, {$push: {"scores": 80}})

This query finds a document with the specified β€˜_idβ€˜ and adds the value 80 to the β€˜scoresβ€˜ array, even if the array already contains the value 80.

On the other hand, the $addToSet operator adds a specified value to an array field only if it does not already exist in the array. If the specified value is an array itself, $addToSet checks if any element in the array already exists in the main array and only adds the entire array as a single element if none of its elements already exists. The syntax for using $addToSet is as follows:

db.collection.update(
   <query>,
   { $addToSet: { <field>: <value> } },
   { <options> }
)

Here, β€˜<field>β€˜ is the array field to which the value is being added and β€˜<value>β€˜ is the value being added. For example, consider the following query:

db.myCollection.update({"_id": ObjectId("5ea1ad2e284b54a77bcc97a4")}, {$addToSet: {"scores": 80}})

This query finds a document with the specified β€˜_idβ€˜ and adds the value 80 to the β€˜scoresβ€˜ array only if it does not already exist in the array.

To summarize, while both operators perform similar tasks of adding elements to an array field, the $push operator adds the element even if it already exists, while the $addToSet operator adds the element only if it does not already exist in the array.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic MongoDB interview β€” then scores it.
πŸ“ž Practice MongoDB β€” free 15 min
πŸ“• Buy this interview preparation book: 100 MongoDB questions & answers β€” PDF + EPUB for $5

All 100 MongoDB questions Β· All topics