从MongoDB中数组元素删除字段 [英] Remove a field from array element in mongodb

查看:301
本文介绍了从MongoDB中数组元素删除字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面我有文件MongoDB中(2.4.5)

I have below document in MongoDB(2.4.5)

{
    "_id" : 235399,
    "casts" : {
        "crew" : [ 
            {
                "_id" : 1186343,
                "withBase" : true,
                "department" : "Directing",
                "job" : "Director",
                "name" : "Connie Rasinski"
            },
            {
                "_id" : 86342,
                "withBase" : true
            }
        ]
    },
    "likes" : 0,
    "rating" : 0,
    "rating_count" : 0,
    "release_date" : "1955-11-11"
}

我想删除withBase从数组元素内提交.. casts.crew

I want to remove withBase filed from array elements inside casts.crew ..

这个我试过

db.coll.update({_id:235399},{$unset: {  "casts.crew.withBase" : 1 } },false,true)

什么都没有改变。

nothing changed.

和尝试这样做。

db.coll.update({_id:235399},{$unset: {  "casts.crew" : { $elemMatch: { "withBase": 1 } } } },false,true)

删除它从文件整个剧组数组。

it removed entire crew array from the document.

可有人请我提供正确的查询?

Can someone please provide me the right query?

推荐答案

抱歉让你们失望,但你的答案

Sorry to disappoint you, but your answer

db.coll.update({
   _id:235399,
   "casts.crew.withBase": {$exists: true}
},{
   $unset: {
      "casts.crew.$.withBase" : true
   }
},false,true)

是不正确的。实际上,它只会从子文档中第一次出现删除值,但由于方式的的位置操作符

的位置$操作者充当第一元件的占位符
  该查询文档匹配

the positional $ operator acts as a placeholder for the first element that matches the query document

您也不能使用$未设置(当你尝试过),因为它不能在阵列工作(而且基本上你试图删除从文档从阵列中键)。也因为拉删除所有的数组,而不是只是它的字段不能以$拉删除它。

You also can not use $unset (as you tried before) because it can not work on arrays (and are you basically trying to remove a key from a document from the array). You also can not remove it with $pull, because pull removes all the array, not just a field of it.

因此​​,据我知道你不能用一个简单的运营商做到这一点。所以不得已做$查找,然后用保存的foreach。你可以看到如何在我的答案做到这一点这里。你的情况,你需要有功能的foreach循环的另一个阵列,通过迭代和删除密钥。我希望你可以修改它。如果没有,我会尽力帮助你。

Therefore as far as I know you can not do this with a simple operator. So the last resort is doing $find and then foreach with save. You can see how to do this in my answer here. In your case you need to have another loop in foreach function to iterate through array and to delete a key. I hope that you will be able to modify it. If no, I will try to help you.

P.S。如果有人看起来方式做到这一点 - 这里的桑德拉的功能

P.S. If someone looks a way to do this - here is Sandra's function

db.coll.find({_id:235399}).forEach( function(doc) {
  var arr = doc.casts.cast;
  var length = arr.length;
  for (var i = 0; i < length; i++) {
    delete arr[i]["withBase"];
  }
  db.coll.save(doc);
});

这篇关于从MongoDB中数组元素删除字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆