1

In the mongo documentation unsetting a field is done with $unset. I can't quite grasp how it works, but it seems like it should be simple.

The following operation uses the $unset operator to remove the tags field:

db.books.update( { _id: 1 }, { $unset: { tags: 1 } } )

My confusion arises when setting what to unset. What is the value 1 for in the $unset clause?

Ryan-Neal Mes
  • 6,003
  • 7
  • 52
  • 77

3 Answers3

6

As per the $unset documentation :-

The $unset operator deletes a particular field.

Syntax : { $unset: { <field1>: "", ... } }

The specified value in the $unset expression (i.e. "") does not impact the operation.

If the field does not exist, then $unset does nothing (i.e. no operation).

So you can use

db.books.update( { _id: 1 }, { $unset: { tags: 1 } } )

OR

db.books.update( { _id: 1 }, { $unset: { tags: 0 } } )

OR

db.books.update( { _id: 1 }, { $unset: { tags: "" } } )

All the above queries will delete tags field.

Hope your doubt is clear now.

Community
  • 1
  • 1
Shrabanee
  • 2,706
  • 1
  • 18
  • 30
  • In the doc, the explanation is simple: "The specified value in the $unset expression (i.e. "") does not impact the operation." More here: https://docs.mongodb.com/manual/reference/operator/update/unset/ – Juan Antonio Oct 25 '17 at 17:24
3

{$unset : { tags : 1 } } will clear the field tags from the document. The value 1 is just to tell that, clear this field tags from the document.

If you want to clear multiple fields, you need to write {$unset : { tags : 1, randomField : 1} } and like that.

You can refer official documentation of $unset for further info.

According to the documentation:

The $unset operator deletes a particular field. Consider the following syntax:

{ $unset: { field1: "", ... } }

The specified value in the $unset expression (i.e. "") does not impact the operation.

If the field does not exist, then $unset does nothing (i.e. no operation).

When used with $ to match an array element, $unset replaces the matching element with null rather than removing the matching element from the array.

Ravi Shankar Bharti
  • 8,922
  • 5
  • 28
  • 52
  • What would happen if I used 0 instead of 1? Does the actual value hold any relevance? – Ryan-Neal Mes Aug 09 '16 at 05:59
  • The actual value 0/1 doesn't hold any relevance. But, i think that is the way that query was modeled. See this for more reference : https://docs.mongodb.com/manual/reference/operator/update/unset/ – Ravi Shankar Bharti Aug 09 '16 at 06:52
0

The $unset operator deletes a particular field.

Meena
  • 97
  • 2