过滤Json响应更新mongodb数据库

o2g1uqev  于 2023-04-05  发布在  Go
关注(0)|答案(2)|浏览(124)

我尝试过滤一个json响应,并使用过滤后的响应更新我的mongodb集合中的几个文档。Json响应看起来像这样:

{"88996940":{"charge":"5","start_count":"10","status":"Completed","remains":"90","currency":"USD"},
"88996961":{"charge":"8","start_count":"50","status":"Completed","remains":"50","currency":"USD"},
"88999796":{"charge":"7","start_count":"80","status":"Completed","remains":"20","currency":"USD"}}

“88996940”、“88996961”和“88999796”是订单ID。
我想过滤“start_count”、“status”和“remains”的值。
我尝试解析它们,但只有当只有一个订单ID时才有效,否则响应为“null”:

JObject responseObject = JObject.Parse(responseContent);
orderStartCount = responseObject1["start_count"].ToString();
orderStatus = responseObject1["status"].ToString();
orderRemains = responseObject1["remains"].ToString();

我还使用了下面的代码来更新一个mongodb文档,但我不知道如何处理多个文档和不同的值。

var filterSingle = Builders<BsonDocument>.Filter.Eq("orderID", orderID);
var update = Builders<BsonDocument>.Update.Set("status", orderStatus)
                                   .Update.Set("start_count", orderStartCount)
                                   .Update.Set("remains", orderRemains);
MyCollection.UpdateOne(filterSingle, update);
8cdiaqws

8cdiaqws1#

JSON对象不是集合;是字典。
集合将是:

[{"charge":"5","start_count":"10","status":"Completed","remains":"90","currency":"USD"},{"charge":"8","start_count":"50","status":"Completed","remains":"50","currency":"USD"},{"charge":"7","start_count":"80","status":"Completed","remains":"20","currency":"USD"}]

区别在于:

  • 集合被括在[]括号中,而字典是一个对象{}
  • 集合具有无键对象:[{},{},{}],字典需要每个对象的键值对:{"": {}, "": {}, "": {}}

TL:DR;将JSON反序列化为Dictionary<int, Entity>,其中Entity是mongoDB集合中的一项。

ukdjmx9f

ukdjmx9f2#

我自己修复了这个问题,我只需要通过响应创建一个循环并提取单个值,下面是代码:

JObject responseObject = JObject.Parse(responseContent);

foreach (var order in responseObject)
{
    string orderID = order.Key;
    string orderStartCount = order.Value["start_count"].ToString();
    string orderStatus = order.Value["status"].ToString();
    string orderRemains = order.Value["remains"].ToString();

    
    var filter = Builders<BsonDocument>.Filter.Eq("orderID", orderID);
    var update = Builders<BsonDocument>.Update.Set("status", orderStatus)
                                             .Set("start_count", orderStartCount)
                                             .Set("remains", orderRemains);
    MyCollection.UpdateOne(filter, update);
}

相关问题