MongoDB How to remove a field from document

摘要: This MongoDB article shows you how to remove a field from document and array.

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

  1. MongoDB : $unset
  2. MongoDB : Modify documents
  3. MongoDB : Query document, Array

上一篇: Jsoup Check Redirect URL
下一篇: Javascript How to call function inside jQuery code
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号