c# - Mongodb 更新或插入 c#
问题描述
我想更新或插入到 mongo 集合“成员”。在这个集合下,我有一个数组 MagazineSubscription。这里的杂志 Code 是独一无二的。请参考示例 JSON。
因此,如果需要使用 C# mongo 驱动程序更新或插入 mongo。
- 首先我需要检查此代码是否存在 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"
}
]
}
]
}
解决方案
将 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
脚步:
- 首先,您需要编写一个过滤器来扫描文档是否存在。您可以检查任意数量的键(本质上是一个文档)。
- 使用您要更新的键(本质上是一个文档)编写更新部分。
- 将 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);
推荐阅读
- azure-application-insights - Application Insights 报告失败但没有日志
- javascript - 无论如何在javascript上将标签转换为带有href的按钮?
- datatable - DataTables 多搜索正在截断单个结果
- swift - SwiftUI - com.apple.main-thread
- c# - 通过 AutoMapper 映射大列表时如何优化每个项目的调用转换器?
- javascript - 如何在 Drupal 8 上重置 Bootstrap 4 工具提示?
- html - 将 html 行拆分为多行
- c - 模块化开发
- javascript - 如何添加到键值对对象(jsx)中的列表
- go - 为什么“int”可以转换为“string”?