首页 > 解决方案 > Mongodb 更新或插入 c#

问题描述

我想更新或插入到 mongo 集合“成员”。在这个集合下,我有一个数组 MagazineSubscription。这里的杂志 Code 是独一无二的。请参考示例 JSON。

因此,如果需要使用 C# mongo 驱动程序更新或插入 mongo。

  1. 首先我需要检查此代码是否存在 2,如果存在则更新一个
  2. 如果不存在插入。

有什么办法可以一步到位。就像它已经存在更新,否则插入。而不是命中两次。因为我的收藏很大。

{ 
    "_id" : ObjectId("5c44f7017en0893524d4e9b1"), 
    "Code" : "WH01", 
    "Name" : "Lara", 
    "LastName" : "John", 
    "DOB" : "12-10-2017", 
    "Gender" : "Male", 
    "Dependents" : [
        {
            "RelationShip" : "Son", 
            "Name" : "JOHN", 
            "DOB" : "01-01-1970", 
            "Gender" : "Male", 
            "Address" : "Paris", 
            "ContactNumber" : "+312233445666"
        }, 
        {
            "RelationShip" : "Wife", 
            "Name" : "Marry", 
            "DOB" : "01-01-1980", 
            "Gender" : "Female", 
            "Address" : "Paris", 
            "ContactNumber" : "+312233445666"
        }
    ]
    "Matrimony" : [
        {
            "Fee" : 1000.0, 
            "FromDate" : "01-01-2015", 
            "ToDate" : "01-01-2017", 
            "Status" : false
        }
    ], 
    "MagazineSubscription" : [
        {
            "MagazineCode" : "WSS", 
            "DateFrom" : "01-05-2018", 
            "DateTo" : "01-01-2020", 
            "PaidAmount" : 1000.0, 
            "ActualCost" : 1500.0, 
            "Status" : false, 
            "DeliveryStatus" : [
                {
                    "ReturnedDate" : "10-01-2019", 
                    "Comment" : "Returned because of invalid address"
                }, 
                {
                    "ReturnedDate" : "10-02-2019", 
                    "Comment" : "Returned because of invalid address"
                }
            ]
        }
    ]
}

标签: c#mongodbmongodb-query

解决方案


将 mongodb 的更新操作与 upsert:true 一起使用。请参考这里:https ://docs.mongodb.com/manual/reference/method/db.collection.update/

这是页面中的示例:

 db.collection.update(
   <query>,
   <update>,
   {
     upsert: <boolean>, //you need this option
     multi: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     arrayFilters: [ <filterdocument1>, ... ]
   }
)

根据您的需要,这里有一个类似的问题: Upserting in Mongo DB using official C# driver

编辑 1

脚步:

  1. 首先,您需要编写一个过滤器来扫描文档是否存在。您可以检查任意数量的键(本质上是一个文档)。
  2. 使用您要更新的键(本质上是一个文档)编写更新部分。
  3. 将 upsert 设置为 true。

Mongodb 将使用您的过滤器来搜索文档。如果找到,它将使用更新部分执行您提到的更新。

如果文档不存在,将使用更新部分中的过滤器键+键创建一个新文档。

希望这能让事情变得清楚,因为我从未使用过 C# mongo 驱动程序。因此,我将无法为您提供确切的语法。

编辑 2

我在这里提供@jeffsaracco 的解决方案:

MongoCollection collection = db.GetCollection("matches");
var query = new QueryDocument("recordId", recordId); //this is the filter

var update = Update.Set("FirstName", "John").Set("LastName","Doe"); //these are the keys to be updated
matchCollection.Update(query, update, UpdateFlags.Upsert, SafeMode.False);

推荐阅读