这是我的 MongoDb 结构的示例:
{
"id" : 1,
"children" : [
{
"id" : 2,
"status" : " fsdfsdf "
},
{
"id" : 3,
"status" : " ffdfg "
},
{
"id" : 4,
"status" : " fsdfsdfsdfdsf "
}
]
}
我想要更新查询..查询必须修剪(删除空格和/或制表符) 所以我的记录将是:
{
"id" : 1,
"children" : [
{
"id" : 2,
"theText" : "fsdfsdf"
},
{
"id" : 3,
"status" : "ffdfg"
},
{
"id" : 4,
"status" : "fsdfsdfsdfdsf"
}
]
}
谢谢
最佳答案
MongoDB 不提供字符串运算符来修剪字符串,但我们可以使用聚合框架构建一个字符串运算符,但此解决方案需要 MongoDB 3.4 或更高版本。
db.coll.aggregate([
{ "$addFields": {
"children": {
"$map": {
"input": "$children",
"as": "child",
"in": {
"id": "$$child.id",
"status": {
"$arrayElemAt": [
{ "$filter": {
"input": { "$split": [ "$$child.status", " " ] },
"as": "ch",
"cond": { "$gt": [ { "$strLenCP": "$$ch" }, 0 ]}
}},
0
]
}
}
}
}
}},
{ "$out": "coll" }
])
我们的管道中只需要一个阶段,即 $project
阶段或 $addFields
阶段。我选择使用 $addFields
自动在结果中包含其他字段。
我们需要对“children”数组中的每个元素应用一个表达式,这对于 $map
来说是一个完美的工作。数组运算符。
在in表达式中,我们简单地$split
我们的子字符串中的字符串,$filter
删除所有长度为0的子字符串得到的数组。
要返回字符串的长度,我们使用 $strLenCP
运算符。
然后我们使用$arrayElemAt
返回唯一剩余的字符串。运算符。
我们管道的最后一个阶段是$out
将结果写入新集合或替换旧集合的阶段。
另一种替代方法是使用 mapReduce
来 trim
空间并使用批量操作更新您的集合:
MapReduce 查询:
db.coll.mapReduce(function() {
emit(
this._id,
this.children.map( child => {
return { "id": child.id, "status": child.status.trim() };
})
); }, function(key, value) {}, {"out": {"inline": 1 }}
)
更新部分留给读者作为练习。
关于mongodb - 修剪记录值/删除空格/制表符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41848031/