DEV Community

Cover image for $Unset, $Pop, $Pull, $PullAll in MongoDB
KAWSAR KABIR
KAWSAR KABIR

Posted on

$Unset, $Pop, $Pull, $PullAll in MongoDB

$unset

If we want to remove a field from a document in a MongoDB collection, we can use the $unset operator. First, let's add some data to the database, then we'll remove a field from that data.

db.persons.insertMany([
  { name: "Kawsar", age: 19, profession: "Frontend Developer" },
  { name: "Emanul", age: 19, profession: "Frontend Developer" },
]);

db.persons.updateOne({ name: "Kawsar" }, { $unset: { age: "" } });
Enter fullscreen mode Exit fullscreen mode
  • In the code above, the age field is removed from the document where name is Kawsar.

$pop

To remove the first or last element of an array in a document, we use the $pop operator. First, let's insert a document into the database:

db.products.insertOne({
  _id: 100,
  quantity: 250,
  instock: true,
  details: { model: "14QQ", make: "Clothes Corp" },
  ratings: [{ by: "Customer007", rating: 4 }],
  tags: ["apparel", "clothing"],
});
Enter fullscreen mode Exit fullscreen mode
  • Here, we have added a document to the products collection.

For example, if we want to remove the first or last item from the ratings array, we can use $pop:

db.products.updateOne(
  { _id: 100 },
  { $pop: { ratings: 1 } } // Use 1 to remove the last element
);

db.products.updateOne(
  { _id: 100 },
  { $pop: { ratings: -1 } } // Use -1 to remove the first element
);
Enter fullscreen mode Exit fullscreen mode

$pull

The $pull operator is used to remove all instances of a specific value from an array in a document.

For example, if we want to remove the clothing tag from the tags array, we can use $pull:

db.products.updateOne({ _id: 100 }, { $pull: { tags: "clothing" } });
Enter fullscreen mode Exit fullscreen mode

$pullAll

The $pullAll operator is used to remove multiple specific values from an array in a document.

For example, if we want to remove multiple tags from the tags array, we can use $pullAll:

db.products.updateOne(
  { _id: 100 },
  { $pullAll: { tags: ["clothing", "apparel"] } }
);
Enter fullscreen mode Exit fullscreen mode
  • In the code above, the tags "clothing" and "apparel" are removed from the tags array in the document with _id: 100.

Top comments (0)