从mongodb中数组中的所有元素中删除字段 [英] Remove a field from all elements in array in mongodb

查看:86
本文介绍了从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"
}

我想从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)

什么都没改变.

并尝试了这个.

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)

不正确.实际上,由于位置运算符有效:

is not correct. Actually it will remove the value, BUT only from the first occurrence of the subdocument, because of the way positional operator works:

位置$运算符充当第一个元素的占位符 与查询文档匹配的

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

您也不能使用$unset(如您之前尝试过的),因为它不能在数组上工作(并且您基本上是在尝试从数组中的文档中删除键).您也不能使用$pull删除它,因为pull删除了所有数组,而不仅仅是数组中的一个字段.

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.

因此,据我所知,您无法使用简单的运算符来执行此操作.因此,最后的方法是先执行$find,然后执行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.如果有人希望这样做-这是 Sandra的功能

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.crew;
  var length = arr.length;
  for (var i = 0; i < length; i++) {
    delete arr[i]["withBase"];
  }
  db.coll.save(doc);
});

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

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