$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: "" } });
- In the code above, the
age
field is removed from the document wherename
isKawsar
.
$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"],
});
- 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
);
$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" } });
$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"] } }
);
- In the code above, the tags
"clothing"
and"apparel"
are removed from thetags
array in the document with_id: 100
.
Top comments (0)