Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB remove a subdocument document from a subdocument

Tags:

c#

mongodb

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

like image 453
John Avatar asked Feb 24 '23 16:02

John


1 Answers

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);
like image 193
Andrei Andrushkevich Avatar answered Feb 26 '23 17:02

Andrei Andrushkevich