更新BsonDocument中数组内的元素

时间:2012-07-19 03:26:05

标签: c# mongodb mongodb-.net-driver

我有一个像这样的“收款人”BsonDocument:

{
  "Token" : "0b21ae960f25c6357286ce6c206bdef2",
  "LastAccessed" : ISODate("2012-07-11T02:14:59.94Z"),
  "Firstname" : "John",
  "Lastname" : "Smith",
  "PayrollInfo" : [{
      "Tag" : "EARNINGS",
      "Value" : "744.11",
    }, {
      "Tag" : "DEDUCTIONS",
      "Value" : "70.01",
    }],
  },
  "Status" : "1",
  "_id" : ObjectId("4fc263158db2b88f762f1aa5")
}

我根据收款人_id检索此文档。

var collection = database.GetCollection("Payee");
var query = Query.EQ("_id", _id);
var bDoc = collection.FindOne(query);

然后,我需要在不同时间更新PayrollInfo数组中的特定对象。所以我在数组中用适当的“Tag”搜索对象,并将“Value”更新到数据库中。我使用以下逻辑来执行此操作:

var bsonPayrollInfo = bDoc["PayrollInfo", null];
if (bsonPayrollInfo != null)
{
    var ArrayOfPayrollInfoObjects = bsonPayrollInfo.AsBsonArray;
    for (int i = 0; i < ArrayOfPayrollInfoObjects.Count; i++)
    {
        var bInnerDoc = ArrayOfPayrollInfoObjects[i].AsBsonDocument;
        if (bInnerDoc != null)
        {
            if (bInnerDoc["Tag"] == "EARNINGS")
            {
                //update here
                var update = Update
                    .Set("PayrollInfo."+ i.ToString() + ".Value", 744.11)
                collection.FindAndModify(query, null, update);
                bUpdateData = true;
                break;
            }
        }
    }
}

if (!bUpdateData)
{
    //Use Update.Push.  This works fine and is not relevant to the question.
}

所有这些代码都运行良好,但我认为我在实现结果方面很麻烦。这样做有更简洁的方法吗?基本上,我试图找到一种更好的方法来更新BsonDocument中数组内的对象。

2 个答案:

答案 0 :(得分:1)

Mongo有一个位置运算符,可以让你对数组中的匹配值进行操作。语法为:field1.$.field2

以下是您如何在Mongo shell中使用它的示例:

db.dots.insert({tags: [{name: "beer", count: 2}, {name: "nuts", count: 3}]})
db.dots.update({"tags.name": "beer"}, {$inc: {"tags.$.count" : 1}})
result = db.dots.findOne()
{ "_id" : ObjectId("50078284ea80325278ff0c63"), "tags" : [ { "name" : "beer", "count" : 3 }, { "name" : "nuts", "count" : 3 } ] }

答案 1 :(得分:1)

将答案放在这里以防万一它可以帮到你。根据@ MrKurt的回答(谢谢!),这是我为修改代码所做的工作。

var collection = database.GetCollection("Payee");
var query = Query.EQ("_id", _id);

if (collection.Count(query) > 0)
{
    //Found the Payee.  Let's save his/her Tag for EARNINGS
    UpdateBuilder update = null;

    //Check if this Payee already has any EARNINGS Info saved.
    //If so, we need to update that.
    query = Query.And(query,
        Query.EQ("PayrollInfo.Tag", "EARNINGS"));

    //Update will be written based on whether we find the Tag:EARNINGS element in the PayrollInfo array
    if (collection.Count(query) > 0)
    {
        //There is already an element in the PayrollInfo for EARNINGS
        //Just update that element
        update = Update
            .Set("PayrollInfo.$.Value", "744.11");
    }
    else
    {
        //This user does not have any prior EARNINGS data.  Add it to the user record
        query = Query.EQ("_id", _id);
        //Add a new element in the Array for PayrollInfo to store the EARNINGS data
        update = Update.Push("PayrollInfo",
                    new BsonDocument {{"Tag", "EARNINGS"}, {"Value", "744.11"}}
                 ); 
    }

    //Run the update
    collection.FindAndModify(query, null, update);
}

它看起来并不比我的原始代码更小,但它更直观,我必须学习很多关于位置操作符的知识!