4

I use 10gen C# driver for MongoDB and I would like to remove a subdocument from a subdocument. I don't know how to do it.

Here's an example of what looks like my document

{
  "_id": "binary_stuff",
  "Name": "MyApplication",
  "Settings": [
    {
      "_id": "binary_stuff",
      "Key": "ImportDirectory",
      "Value": "C:\data",
      "Overrides": [{
             "_id": "binary_stuff",
             "Name": "PathDirectory",
             "Value": "C:\anotherData"
       }]
    },
}

And I want to delete the Override which Name is PathDirectory. Here's the query I wrote but it doesn't work. I have no error.

var query = Query.And(Query.EQ("_id", applicationId), Query.EQ("Settings.Key", "ImportDirectory"), Query.EQ("Settings.$.Overrides.Name", "PathDirectory"));
Run(database => database.Applications().Remove(query));

Thanks for any help. John

John
  • 4,351
  • 9
  • 41
  • 57

1 Answers1

8

you should to use $pull operation for delete item from array.

        var query = Query.And(Query.EQ("_id", applicationId),
                         Query.EQ("Settings.Key",  "ImportDirectory"));
        var update = Update.Pull("Settings.$.Overrides", new BsonDocument(){
            { "Name", "PathDirectory" }
        });
        database.Applications().Update(query, update);
Andrei Andrushkevich
  • 9,905
  • 4
  • 31
  • 42
  • I tried with this query with your code : var query = Query.And(Query.EQ("_id", applicationId), Query.EQ("Settings.Key", "ImportDirectory")); but it does nothing – John Jul 05 '11 at 15:09
  • This time, the override is still not removed, but instead I have another subdocument Settings[0]: {} at the Settings level. Look this document: { "_id": "binary_stuff", "Name": "MyApplication", "Settings": [ { "_id": "binary_stuff", "Key": "ImportDirectory", "Value": "C:\data", "Overrides": [{ "_id": "binary_stuff", "Name": "PathDirectory", "Value": "C:\anotherData" }], "Settings[0]": {}, }, } – John Jul 05 '11 at 15:39
  • And if I try this query: var query = Query.And(Query.EQ("_id", applicationId), Query.EQ("Settings.Key", "ImportDirectory"), Query.EQ("Settings.$.Overrides.Name", "PathDirectory")); Nothing happens – John Jul 05 '11 at 15:42
  • @John Smith: plz, try to check last solution – Andrei Andrushkevich Jul 05 '11 at 15:53
  • Thanks Andrei. For me the following syntax worked. `var query = Query.And(Query.EQ("_id", applicationId), Query.EQ("Settings.Key", "ImportDirectory")); var update = Update.Pull("Settings.Overrides", new BsonDocument(){ { "Name", "PathDirectory" } }); database.Applications().Update(query, update);`. Note that the "$" sign is missing in the pull statement. – Jardalu Nov 21 '13 at 22:38