0

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"
      }
    }
  ]
}

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 ")
    });
});

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.

3 Answers 3

2

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"} }}
);
Sign up to request clarification or add additional context in comments.

Comments

1

You can use $pull to delete specific elements from the array

db.geojsons.update({}, {
      $pull: {features: {'properties.TYPE':'8003'}}
    }, {multi:true})

Comments

-1

I guess in this case the correct solution is reading the matching documents, modify and save them again. So simply create a search query that matches the documents you want: remove the elements in the array that you don't want and save it again.

Moreover, this statement is not doing what you want:

db.collection.deleteOne(
    { "feature.properties.TYPE": "8003"  }            
);

In fact it is searching for a document that has structure such that feature.properties.TYPE matches it like this:

{
  "type": "FeatureCollection",
  "features": {
      "properties": {
        "TYPE": "8003"
      }
    }
}

And this is definitely not the structure you have.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.