0

I have following data structure:

db.objects
{
    "_id" : 1,
    "name" : "object name",
    "type" : "rectangle",
    "area" : {
        "position_x1" : 0,
        "position_y1" : 0,
        "position_x2" : 0,
        "position_y2" : 0
    },
    "dimension" : {
        "width" : 0,
        "height" : 0
    }
}

I want to replace/update "area" and "dimension" separately for a document in objects collection with "_id" = 1.

[?] Please let me know how can i achieve using MongoDB C# driver.

theGeekster
  • 6,081
  • 12
  • 35
  • 47

1 Answers1

3

This is a very simple use of the $set operator. So essentially the update form is:

db.objects.update(
    { "_id": 1 },
    {
        "$set": {
            "area": { /* all of your object properties */ },
            "dimension": { /* all of your object properties */ }
        }
    }
)

Alternately you do them separately:

db.objects.update(
    { "_id": 1 },
    {
        "$set": {
            "area.position_x1": 1,
            "area.position_y1": 1,
            "dimension.width": 1 
        }
    }
)

According to you actual needs.

Or as C# type code with a Builder:

var query = Query.EQ("_id",1);

var update = Update.Set("area.position_x1", 1)
    .Set("area.position_y1", 1)
    .Set("dimension.width", 1);

MongoCollection<Class>.update(query, update);
Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
  • Neil can you please tell how to achieve this using MongoDB C# driver ? – theGeekster Apr 18 '14 at 15:09
  • @theGeekster There should not be much difference in the implementation, you are just creating BSON documents to match the JSON form. Unfortunately it has hit 2 a.m here for me on a public holiday so this will be my sign-off for the night. Give it a try, it isn't really that hard, and it's a learning experience. – Neil Lunn Apr 18 '14 at 15:49
  • @theGeekster So when I have found a moment to come back to this, an example exists – Neil Lunn Apr 19 '14 at 04:46
  • Thanks Neil for your response. Though I also found it myself with: var update = Update.AddToSet("area.x1", X1).AddToSet("area.X2", X2).AddToSet("dimension.width", width).AddToSet("dimension.height", height); – theGeekster Apr 21 '14 at 12:52