mongodb - Mongo DB - UpdateMany 列数据
问题描述
我有一个带有字典字段的数据库表,其中键是字符串,值是一个 int 列表。(Dictionary<string,List<int>>())
但现在我已经将该字典更改为(Dictionary<string,list<string>>())
。但是数据库表具有旧字典值(list<int>
)的现有记录。同时从我得到了序列化错误的表。有任何方法可以将这些值从 int 更新为字符串。我的意思是 int 值列表将替换为字符串列表或将 int 值更改为字符串。我可以用 updateMany 做到这一点() mongodb 函数?如果是,那将如何?这是一个示例记录。assignscopes 和 scopes 是一本字典
{
"_id" : "14390b07-9407-4abb-9504-34eb02d504c1",
"Name" : "Bhavin Varsur",
"UserName" : "b10",
"Email" : "bhavin@gmail.com",
"MobileNumber" : "1016345823",
"Applications" : [
{
"_id" : "19e1b485-3077-49ba-81a2-13dec1abc012",
"UserRoles" : [
{
"Name" : "Super Admin",
"Permissions" : null,
"AssignScopes" : {
"Branch" : [
0
],
"Unit" : [],
"Option" : []
},
"Scopes" : {
"Region" : [
3
],
"Branch" : [
4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
"Unit" : [
1, 2, 3, 4, 5, 44, 6, 7, 8, 9, 10, 11, 52, 12, 13, 14, 15, 16, 17, 18
],
"Option" : [
1, 2, 3, 4, 5, 6, 7, 8, 9
]
}
}
]
}
这是将字典值更改为字符串后的模型
public class UserRole
{
public string Name { get; set; }
public List<string> Permissions { get; set; }
[BsonDictionaryOptions(DictionaryRepresentation.Document)]
public Dictionary<string, List<string>> AssignScopes { get; set; } = new Dictionary<string, List<string>>();
[BsonDictionaryOptions(DictionaryRepresentation.Document)]
public Dictionary<string, List<string>> Scopes { get; set; } = new Dictionary<string, List<string>>();
}
解决方案
您可以使用嵌套映射函数运行管道更新命令,如下所示:
db.collection.updateMany({},
[
{
$set: {
Applications: {
$map: {
input: "$Applications",
as: "a",
in: {
_id: "$$a._id",
UserRoles: {
$map: {
input: "$$a.UserRoles",
as: "ur",
in: {
Name: "$$ur.Name",
Permissions: "$$ur.Permissions",
AssignScopes: {
Branch: {
$map: {
input: "$$ur.AssignScopes.Branch",
as: "b",
in: {
$toString: "$$b"
}
}
},
Unit: "$$ur.Unit", // do another map if these are also integers
Option: "$$ur.Option" // do another map if these are also integers
},
Scopes: {
Region: {
$map: {
input: "$$ur.Scopes.Region",
as: "r",
in: {
$toString: "$$r"
}
}
},
Branch: {
$map: {
input: "$$ur.Scopes.Branch",
as: "b",
in: {
$toString: "$$b"
}
}
},
Unit: {
$map: {
input: "$$ur.Scopes.Unit",
as: "u",
in: {
$toString: "$$u"
}
}
},
Option: {
$map: {
input: "$$ur.Scopes.Option",
as: "o",
in: {
$toString: "$$o"
}
}
}
}
}
}
}
}
}
}
}
}
])
推荐阅读
- javascript - 无法插值
- android-nestedscrollview - 在 NestedScrollView 中使用 PagedListAdapter
- ios - 如何设置应用程序委托中可访问的 XCUItest 类的参数
- html - 防止强制字段星号标签换行
- java - 在不使用任何文件路径的情况下解码和解压缩文件
- c# - Caliburn.Micro WPF:如何创建具有依赖项的新 ViewModel?
- python - 使用不区分大小写的字符串访问python字典
- mysql - 如何使用 Ansible 为 MySQL/MariaDB root 用户设置和保存随机密码?
- c# - 突出显示 textbox-winform c# 中的错误行
- angular - Angular 4+ Dependency Injection - Getting the closest host component out of more possibilities