如何更新mongo db c#中的所有记录
how to update mongo db all records in c#
我有 mongo 数据库集合,用于存储 JSON。
错误地在一个集合的所有记录中更新了一个元素值。
我将如何更新特定元素?
我的 json 就像
{
status:
{
name:"john",
value: "12345678903333.444"
}
}
这里的值属性值应该是长字段,值会被
替换
{
status:
{
"name":"john",
"value": 1234567890
}
}
应将值修剪为现有值的前 10 个字符。
更新后(来自@mickl 回答),
转换为 Int 也有错误!
你可以使用$substr operator with $toDouble to convert string to number and then redirect aggregation results into the same collection using $out(基本上会更新它的所有文件),试试Mongo shell:
db.col.aggregate([
{
$addFields: {
"status.value": { $toDouble: { $substr: [ "$status.value", 0, 10 ] } }
}
},
{
$out: "col"
}
])
或者在 C# 代码中:
var addFieldsBody = "{ $addFields: { \"status.value\": { $toDouble: { $substr: [ \"$status.value\", 0, 10 ] } } } }";
Col.Aggregate()
.AppendStage<BsonDocument>(BsonDocument.Parse(addFieldsBody))
.Out("col");
我有 mongo 数据库集合,用于存储 JSON。 错误地在一个集合的所有记录中更新了一个元素值。
我将如何更新特定元素?
我的 json 就像
{
status:
{
name:"john",
value: "12345678903333.444"
}
}
这里的值属性值应该是长字段,值会被
替换{
status:
{
"name":"john",
"value": 1234567890
}
}
应将值修剪为现有值的前 10 个字符。
更新后(来自@mickl 回答),
转换为 Int 也有错误!
你可以使用$substr operator with $toDouble to convert string to number and then redirect aggregation results into the same collection using $out(基本上会更新它的所有文件),试试Mongo shell:
db.col.aggregate([
{
$addFields: {
"status.value": { $toDouble: { $substr: [ "$status.value", 0, 10 ] } }
}
},
{
$out: "col"
}
])
或者在 C# 代码中:
var addFieldsBody = "{ $addFields: { \"status.value\": { $toDouble: { $substr: [ \"$status.value\", 0, 10 ] } } } }";
Col.Aggregate()
.AppendStage<BsonDocument>(BsonDocument.Parse(addFieldsBody))
.Out("col");