更新嵌入文档中的MongoDB官方C#驱动程序驱动程序、文档、官方、MongoDB

2023-09-03 09:50:20 作者:¤萌小呆¤

如果我有一个公司集合,其中包含嵌入的部门:

If I have a Company collection which contains embedded Divisions:

{ 
  "_id": 1 
  "_t": "Company", 
  "Name": "Test Company" 
  "Divisions": [ 
    { 
       "_id": 1 
       "_t": "Division", 
       "Name": "Test Division 1" 
    }, 
    { 
       "_id": 2 
       "_t": "Division", 
       "Name": "Test Division 2" 
    } 
  ] 
} 

什么是使用官方10gen公司的C#的驱动程序? (最新的0.9版本。)

What is the best way to save/update an entire Division when using the official 10gen C# driver? (The latest 0.9 release.)

我用Update.AddToSetWrapped添加部门,而且工作得很好,但我也希望能够根据他们的_id更新文件。

I'm using Update.AddToSetWrapped to add Divisions, and that works fine, but I'd also like to be able to update documents depending on their _id.

例如,如果我定义了以下更新方法:

For example, if I define the following Update method:

public void UpdateDivision(IDivision division) 
{ 
  var mongo = MongoServer.Create(_connectionString); 
  var database = mongo.GetDatabase(_databaseName); 
  var query = Query.EQ("_id", division.CompanyId); 
  var update = Update.AddToSetWrapped("Divisions", division); 
  database.GetCollection<Company>("Company") 
          .Update(query, update, UpdateFlags.Upsert, SafeMode.True); 
} 

和调用它像这样:

var division = GetDivisionById(1); 
division.Name = "New Name"; 
UpdateDivision(division);

司然后一个新的实例将被添加到该组,因为虽然_id仍然是1,该名称是不同的,因此,它是一个唯一的文档。

Then a new instance of Division will be added to the set, because although the "_id" is still 1, the Name is different, and therefore it is a unique document.

那么,什么是有更新整个嵌入式文档的好办法?

So what is there a good way to update a whole embedded document?

直到我想出了一个更好的解决办法,我要第一个 $拉原处,然后 $ addToSet 与修改后的部门。这工作,但显然是不理想的,因为它会执行两个独立的更新。

Until I come up with a better solution I am going to first $pull the original Division and then $addToSet with the modified Division. That works but is obviously not ideal as it performs two separate updates.

推荐答案

您可以使用的MongoDB的位置阵列修改功能一次更新数组中的一个整师如下:

You could use the positional array modification feature of MongoDB to update an entire division in the array at once as follows:

var division = GetDivisionById(1);
division.Name = "New Name";
// change any other properties of division you want
collection.Update(
    Query.EQ("Divisions._id", 1),
    Update.Set("Divisions.$", BsonDocumentWrapper.Create<IDivision>(division))
);

关键的东西怎么回事是:

The key things going on here are:

使用$,在Update.Set的 在自Update.Set需要BsonValue作为第二个参数,我们必须使用BsonDocumentWrapper保持分裂值(IDivision类型参数创建套nominalType在序列化IDivision这会导致_t鉴别被写入)