0

我有一个像这样的“收款人”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 数组中的特定对象。因此,我在数组中搜索具有适当“标签”的对象,并将“值”更新到数据库中。我使用以下逻辑来做到这一点:

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 中数组内的对象。

4

2 回答 2

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 } ] }
于 2012-07-19T03:46:59.880 回答
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);
}

它看起来并不比我的原始代码少,但它更直观,而且我学到了很多关于位置运算符的知识!

于 2012-07-20T22:00:50.923 回答