MongoDB How to remove a field from document
By:Roy.LiuLast updated:2019-08-17
	    This MongoDB article shows you how to remove a field from document and array.
1. Remove a field from Documents
Sample of document, and you want to remove the field “affLink”.
domain.json
      "_id" : 1,
      "domain" : "mkyong.com",
      "affLink" : "abc"
To remove a field from all documents, set {multi: true}, else only the field of the first matched document will be removed.
db.domain.update({},{$unset: {affLink:1}},{multi: true});
Output
domain.json
      "_id" : 1,
      "domain" : "mkyong.com"
2. Remove a field from Array
Prior to MongoDB 2.6, there is still no official function to remove a field from the array. To fix it, you need to write a script :
person.json
   _id: 1,
   name: "mkyong",
   addresses: [
	  street: "99 The Rock Street",
	  city: "Boston",
	  state: "MA",
	  zip: "66666"
	},
	  street: "88 WWF Street",
	  city: "Boston",
	  state: "MA",
	  zip: "77777"
Loop over the documents and remove field “state” from the array one by one.
 
 db.person.find({}).forEach(function(doc) {
	var address = doc.addresses;
	for(var i = 0; i < address.length; ++i) { 
		var x = address[i];
		delete (x["state"]);
	db.person.save(doc);
});
Output
person.json
   _id: 1,
   name: "mkyong",
   addresses: [
	  street: "99 The Rock Street",
	  city: "Boston",
	  zip: "66666"
	},
	  street: "88 WWF Street",
	  city: "Boston",
	  zip: "77777"
References
From:一号门
Previous:Jsoup Check Redirect URL

COMMENTS