MongoDB Remove a field from array

摘要: Prior to MongoDB 2.6, there is no official function to $unset a field from array document.

Prior to MongoDB 2.6, there is no official function to $unset a field from array document.

Note

  1. $unset is not working with arrays
  2. $pull is used to remove the entire record, not a particular field.

1. Arrays Documents

In this article, we will show you how to remove the field “countryName” from below array.

> db.hosting.findOne();
      "_id" : 39,
      "domain" : "mkyong.com",
      "countryStat" : [
                 "countryCode" : "us",
                 "countryName" : "United States",
                 "count" : 2170
         },
                 "countryCode" : "il",
                 "countryName" : "Israel",
                 "count" : 22
         },

2. Remove field from Arrays Documents

To remove fields from array, you need to write a script like this :

db.hosting.find({_id: 39 }).forEach(function(doc) {
	var countries = doc.countryStat;
	for(var i = 0; i < countries.length; ++i) { 
		var x = countries[i];
		delete (x["countryName"]);
	db.hosting.save(doc);
});

Output

> db.hosting.findOne();
      "_id" : 39,
      "domain" : "mkyong.com",
      "countryStat" : [
                 "countryCode" : "us",
                 "count" : 2170
         },
                 "countryCode" : "il",
                 "count" : 22
         },

References

  1. MongoDB $pull documentation
  2. JIRA : Use positional operator to update all items in an array

上一篇: Spring Caching and Ehcache example
下一篇: Ehcache hello world example
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

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

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

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