How To Remove A Field In Mongodb
In this MongoDB tutorial, we are going to hash out "MongoDB remove a field from the certificate". Nosotros will also cover this with different operations and examples. These are the post-obit topics that nosotros are going to cover in this tutorial:
- How to remove a field from the documents in MongoDB
- MongoDB remove fields from the document
- MongoDB remove a field from the documents matching query
- Remove a field from the documents using MongoDB compass
- MongoDB remove a field from one certificate
- MongoDB remove a field from all documents
- Remove a field from the documents using python
How to remove a field from the documents in MongoDB
In MongoDB, The $unset operator is used to delete or remove a item field. Consider the following syntax:
{ $unset: { <field1>: "", ... } }
When we define the value in the $unset expression does non bear upon the operation. If y'all desire to specify an <field> in an embedded certificate or an array use dot (.) notation.
If the field does non be in the documents then $unset does nothing. The update() operation uses the $unset operator to remove the fields. You will more understand with the help of an instance so allow's become started;
Case:
In this example, nosotros apply the update() operation that uses the $unset operator to remove the field from the first document.
The following documents were inserted into the items collection.
db.items.insertMany([ {"_id": 1, "item": "almonds", "description": "almond clusters", "instock": 120, "Review": true }, {"_id": 2, "item": "breadstuff", "clarification": "raisin and nut bread", "instock": fourscore, "Review": true }, {"_id": 3, "item": "pecans", "clarification": "candy-coated pecans", "instock": 60 } ])
Afterward inserting the documents use the below query to remove the field from the first document.
db.items.update( { }, { $unset: { Review: " " }} )
In the update() operation { } is used to specify the document field which yous desire to update. By default, it selects the commencement document. The $unset operator will update and remove the Review field from the outset document.
We successfully remove a field from the documents. The notice() method is used to return all the documents of the collection.
Read: Create index in MongoDB
MongoDB remove fields from the document
We can remove multiple fields from the documents. Like if we desire to remove a field from all the documents field then nosotros employ the updateMany() method.
The updateMany() method volition check all the documents of the collection and the $unset operator will remove all the divers fields.
Yous will more empathize with the assistance of an example so let'due south get started.
Example:
In this case, we apply the updateMany() operation that uses the $unset operator to remove the certificate fields.
The following documents were inserted into the sales collection
db.sales.insertMany([ {"_id": 1, "item": "abc", "price": NumberDecimal("10"), "quantity": 2, "appointment": ISODate("2014-03-01T08:00:00Z")}, {"_id": 2, "item": "jkl", "price": NumberDecimal("20"), "quantity": one, "engagement": ISODate("2014-03-01T09:00:00Z")}, {"_id": 3, "particular": "xyz", "cost": NumberDecimal("v"), "quantity": ten, "date": ISODate("2014-03-15T09:00:00Z")}, {"_id": 4, "detail": "xyz", "cost": NumberDecimal("5"), "quantity": 20, "date": ISODate("2014-04-04T11:21:39.736Z")}, {"_id": 5, "item": "abc", "toll": NumberDecimal("ten"), "quantity": 10, "date": ISODate("2014-04-04T21:23:13.331Z")}, {"_id": six, "particular": "def", "price": NumberDecimal("7.5"), "quantity": v, "engagement": ISODate("2015-06-04T05:08:13Z")}, {"_id": 7, "item": "def", "price": NumberDecimal("vii.five"), "quantity": 10, "date": ISODate("2015-09-10T08:43:00Z")}, {"_id": 8, "item": "abc", "price": NumberDecimal("10"), "quantity": 5, "date": ISODate("2016-02-06T20:20:13Z")} ])
Output:
Now, nosotros utilise the status and remove the fields from the documents:
db.sales.updateMany({ },{$unset:{ quality: " ", quantity: " "}})
Here, we used the updateMany() method and set the $unset operator to remove the two fields quality and quantity from the documents.
Remember that, If the field does non exist in the documents then $unset does nothing.
Nosotros successfully removed the quantity field from all the documents and there is no field related to quality then the $unset operator does naught.
Read: MongoDB Auto Increment ID
MongoDB remove a field from the documents matching query
In this topic, we will remove a field from the documents that match the query with help of an case.
Example:
The following documents were inserted into the person collection:
db.person.insertMany([ {"Name" : "David", "Historic period" : 22, "Gender" : "Male" }, {"Name" : "Mary", "Age" : 22, "Gender" : "Female" }, {"Name" : "Peter", "Age" : 24, "Gender" : "Male" }, {"Name" : "Linda", "Age" : 23, "Gender" : "Female" } ])
Side by side, nosotros will use the matching query and remove fields from the documents.
db.person.updateMany( { }, { $unset: { "Age": " ", "Class": " "}} )
Hither, nosotros used the updateMany() method and set the $unset operator to remove the two fields Age and Grade from the documents.
E'er exercise recollect, the $unset offset matches the fields with the documents and If whatever of the fields do non exist in the documents then $unset does nothing.
We successfully removed the Historic period field from all the documents past matching query and there is no field related to Course then the $unset operator does nothing.
Read: Missing before statement MongoDB
Remove a field from the documents using MongoDB compass
In MongoDB Compass, we tin can edit or remove a field from the documents in the List or Table view.
Note that, modifying documents is not permitted in MongoDB Compass Readonly Edition.
To remove a field from the documents in MongoDB Compass you take to follow the below steps:
- Open up the MongoDB Compass
- Select the database and collection in which y'all want to remove the document fields
- Select the view tab based on whether yous want to view your documents in Listing, JSON, or Table view:
- To change or remove a document field, hover over the certificate and click on the pencil icon
- After clicking on the pencil icon, the document enters into edit mode.
- Here, we tin can perform many tasks every bit delete or remove the field, add together a new field, and modify an existing field.
- So to remove or delete a field of the document click the X icon to the left of the field:
- Once you selected the marked field then it appears in reddish colour
- Here nosotros are removing the instock field from the documents.
- Later end the editing, Click on the UPDATE button and the field volition be removed or deleted from the documents.
- To exit or edit mode and cancel all unfinished changes to the document click on the Abolish button.
We successfully removed the field from the documents using MongoDB Compass.
Read: MongoDB two-phase commit
MongoDB remove a field from i document
In MongoDB, we can as well remove a field from ane document from the collection. Let's sympathise with the help of an case.
Instance:
The following documents were inserted into the detail collection:
db.detail.insertMany([ {"Manufacturer":"Honda", "Model":"City", "Color":"Black"}, {"Manufacturer":"Tata", "Model":"Altroz", "Color":"Golden"}, {"Manufacturer":"Honda", "Model":"Civic", "Colour":"Cherry-red"}, {"Manufacturer":"Hyundai", "Model":"i20", "Color":"white"}, {"Manufacturer":"Maruti", "Model":"Swift", "Color":"Blue"} ])
Output:
Afterwards inserting the documents into the collection, we apply a query and remove a field from a document.
db.detail.update( { "Color": "white" }, { $unset: { "Model": " " }} )
Hither, the update() method is used to update ane document. And, the $unset operation is used to remove the field.
In the update method, we write the query in this fashion where the Color is white $unset will remove the Model field.
We successfully removed the Model field where the Color is white. Here, the discover() method is used to retrieve all the documents of the collection.
Read: MongoDB shutting down with code 48
MongoDB remove a field from all documents
Sometimes equally per the question need, we have to remove a detail field from all the documents. We can remove a detail field from all documents by using the updateMany() method.
And, define the field name by using the $unset operator that will assist usa to remove the field from all the documents.
Let'south more than empathize with the help of an example.
Example:
The following documents were inserted into the example collection:
db.case.insertMany([ { "_id": i, "name": "John", "age": 21, "address": "Highway 37, Canada"}, { "_id": 2, "name": "Peter", "age": 23, "address": "Lowstreet 27,Us"}, { "_id": 3, "name": "Amy", "age": 22, "address": "Apple st 652, UK"}, { "_id": 4, "name": "Hannah", "age": 26, "accost": "Mountain 21, Canada"}, { "_id": 5, "name": "Michael", "historic period": 24, "address": "Valley 345, Australia"} ])
Afterward inserting the documents into the collection, Let'southward remove the age field from all the documents using the following query:
db.case.updateMany( { }, { $unset: { "age": " " }} )
Hither, we used the updateMany() method to employ the condition to all the documents of the collection. The $unset operator is used to remove the age field from all the documents.
Nosotros successfully removed a field from all the documents of the collection.
Read: MongoDB detect multiple conditions
Remove a field from the documents using python
In this topic, nosotros will larn to remove a field from the documents of MongoDB using python. The update() method is used in python to modify the existing document.
And, nosotros have to define the parameters in this method. The $unset is used to remove a field from the documents.
Now, we more sympathise with the help of an case:
Example:
The following documents were inserted into the information collection:
db.data.insertMany([ {"_id": i, "name": "Smith", "class": 11, "subject": "Scientific discipline/Maths"}, {"_id": 2, "proper name": "Tom", "form": 12, "subject": "Commerce"}, {"_id": three, "name": "Adam", "course": 12, "Branch": "Commerce/Maths"}, {"_id": 4, "name": "Bob", "course": 11, "subject": "Arts"} ])
Now, nosotros remove the grade field where _id is two using python. The post-obit script is used to remove a field:
from pymongo import MongoClient # Create a pymongo client client = MongoClient('localhost', 27017) # database example db = client['mydatabase'] # collection instance doc = db['data'] # Remove a single field from the documents res = doc.update( { "_id": ii }, { "$unset": { "class": " " }} ) print(res)
Here, we import the pymongo library that is used to communicate MongoDB server. And, used the MongoClient class that enables to make the successful MongoDB server connection.
After that access the database and collection, mydatabase, and data respectively. The update method uses the $unset operator to remove the class field where "_id: 2″ document.
Afterward executing this python code, this will generate the following output:
{'n': 1, 'nModified': ane, 'ok': 1.0, 'updatedExisting': True}
This "nModified: i" tells that one document is successfully modified from the collection.
At present, you tin can check the documents of the collection that it is updated or not by using the following code:
from pymongo import MongoClient # Create a pymongo client customer = MongoClient('localhost', 27017) # database example db = client['mydatabase'] # collection instance doc = db['data'] # Remember all the document of the collection for remove_doc in doc.detect(): print(remove_doc)
Here, The find() method is used to render all the documents of the drove. The code will call back all the documents of the data collection:
We Successfully removed a field from the document using python.
You may also like to read the following tutorials.
- MongoDB Update Documents
- Export MongoDB to CSV
- MongoDB join 2 collections
- MongoDB discover multiple values
- Import CSV into MongoDB
- MongoDB text search partial words
- MongoDB get collection size
And so, in this tutorial, we have discussed "MongoDB remove a field from the document. And we have besides covered the following topics.
- How to remove a field from the documents in MongoDB
- MongoDB remove fields from the certificate
- MongoDB remove a field from the documents matching query
- Remove a field from the documents using MongoDB compass
- MongoDB remove a field from one document
- MongoDB remove a field from all documents
- Remove a field from the documents using python
After working for more than 15 years in the Software field, especially in Microsoft technologies, I accept decided to share my good knowledge of SQL Server. Cheque out all the SQL Server and related database tutorials I have shared here. Most of the readers are from countries like the United states, the United Kingdom, New Zealand, Australia, Canada, etc. I am also a Microsoft MVP. Check out more here.
Source: https://sqlserverguides.com/mongodb-remove-a-field-from-the-document/#:~:text=documents%20using%20python-,How%20to%20remove%20a%20field%20from%20the%20documents%20in%20MongoDB,%22%2C%20...%20%7D%20%7D
0 Response to "How To Remove A Field In Mongodb"
Post a Comment