Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to search for a record (field) and then delete it in MongoDB?
To search for a field and then delete it in MongoDB, use $exists to find documents containing the field, then $unset to remove it. The $unset operator deletes a particular field from documents.
Syntax
db.collection.update(
{ "fieldName": { $exists: true } },
{ $unset: { "fieldName": "" } },
{ multi: true }
);
Sample Data
Let us create a collection with documents ?
db.demo562.insertMany([
{ "Name": "Chris", "Age": 21 },
{ "Age": 20 },
{ "Name": "David", "Age": 23 }
]);
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5e8f4ae854b4472ed3e8e872"),
ObjectId("5e8f4ae954b4472ed3e8e873"),
ObjectId("5e8f4aea54b4472ed3e8e874")
]
}
Display all documents from the collection ?
db.demo562.find();
{ "_id" : ObjectId("5e8f4ae854b4472ed3e8e872"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5e8f4ae954b4472ed3e8e873"), "Age" : 20 }
{ "_id" : ObjectId("5e8f4aea54b4472ed3e8e874"), "Name" : "David", "Age" : 23 }
Example: Search and Delete Field
Search for documents with a "Name" field and delete that field ?
db.demo562.update(
{ Name: { $exists: true } },
{ $unset: { "Name": "" } },
{ multi: true }
);
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })
Verify Result
Display documents to confirm the "Name" field has been removed ?
db.demo562.find();
{ "_id" : ObjectId("5e8f4ae854b4472ed3e8e872"), "Age" : 21 }
{ "_id" : ObjectId("5e8f4ae954b4472ed3e8e873"), "Age" : 20 }
{ "_id" : ObjectId("5e8f4aea54b4472ed3e8e874"), "Age" : 23 }
Key Points
-
$exists: truematches documents that contain the specified field. -
$unsetremoves the field entirely from matched documents. -
multi: trueapplies the operation to all matching documents.
Conclusion
Use $exists to search for documents containing a specific field, then $unset to remove that field. The multi: true option ensures all matching documents are updated in a single operation.
Advertisements
