mongoDB从数组中删除 [英] mongoDB delete from array

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

问题描述

我想知道如何从mongoDB中的数组中删除某些元素. 我将以下json保存在集合geojsons中:

I am wondering how I can delete certain elements from an array in mongoDB. I have the following json saved in the collection geojsons:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {
        "ID": "1753242",
        "TYPE": "8003"
      }
    },
    {
      "type": "Feature",
      "properties": {
        "ID": "4823034",
        "TYPE": "7005"
      }
    },
    {
      "type": "Feature",
      "properties": {
        "ID": "4823034",
        "TYPE": "8003"
      }
    }
  ]
}

我想删除数组features中的每个元素,其中properties.TYPE等于8003. 我使用以下语句尝试了此操作,但它并未删除任何内容.

And I want to delete every element in the array features, where properties.TYPE equals 8003. I tried it with the following statement, but it does not delete anything.

db.geojsons.aggregate([
{$match: {'features': {$elemMatch : {"properties.TYPE": '8003' }}}},
{$project: {
    features: {$filter: {
        input: '$features',
        as: 'feature',
        cond: {$eq: ['$$feature.properties.TYPE', '8003']}
    }}
}}
])
.forEach(function(doc) {
    doc.features.forEach(function(feature) {
        db.collection.deleteOne(
            { "feature.properties.TYPE": "8003"  }            
        );
        print( "in ")
    });
});

有人知道,为什么这不删除任何内容,或者如何删除匹配的元素? 对我来说,故障似乎在forEach内部,因为print语句已按预期执行.

Does anybody know, why this does not delete anything or how to delete the matching elements? For me it seems that the failure is inside the forEach, since the print statement gets executed as expected.

推荐答案

此处无需aggregation,您可以使用 $ pull " rel ="nofollow noreferrer" >更新

No need of aggregation here, you can use $pull of update

db.geojsons.update(
   { "type": "FeatureCollection" }, //or any matching criteria
   {$pull: { "features": { "properties.TYPE": "8003"} }}
);

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

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