Update or replace an embedded document in MongoDB collection

半世苍凉 提交于 2019-12-18 09:51:32

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/23154540/update-or-replace-an-embedded-document-in-mongodb-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!