在MongoDB中,如何使用按当前值运行的函数更新嵌套文档的值?
我正在尝试修剪嵌套文档中的字段价值,并且为了我的生命,我无法弄清楚如何使其正常工作。
我想在所有文档的代码
字段上运行$ TRIM,以便从MongoDB的Rest中删除前导和尾随空间。
我正在使用MongoDB 4.2。
我的文档结构如下:
{
"_id": "root_id",
"products": [
{
"id": "p1",
"code": "TRAILING "
},
{
"id": "p2",
"code": " LEADING"
}
{
"id": "p3",
"code": "CLEAN"
}
]
}
I'm trying to $trim the value of field within a nested document and for the life of me have not been able to figure out how to get it to work.
I want to run $trim on the code
field of all documents so that both leading and trailing spaces are removed from the documents at-rest in MongoDB.
I'm using MongoDB 4.2.
My document structure is as follows:
{
"_id": "root_id",
"products": [
{
"id": "p1",
"code": "TRAILING "
},
{
"id": "p2",
"code": " LEADING"
}
{
"id": "p3",
"code": "CLEAN"
}
]
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以工作使用聚合管道更新 for MongoDB版本4.2。
$ set
- set产品
字段值。1.1。
$ map
- 迭代产品
数组并返回新数组。1.1.1。
$ MERGEOBJECTS
- 合并当前对象($$ THIS
)和与code
字段来自 1.1.1.1.1.1 。 /p>1.1.1.1。
$ TRIM
-Trim代码
值。并使用
{multi:true}
用于更新多个文档。示例mongo playground
You can work the Updates with Aggregation Pipeline for MongoDB version 4.2.
$set
- Setproducts
field value.1.1.
$map
- Iterate theproducts
array and return a new array.1.1.1.
$mergeObjects
- Merge current object ($$this
) and object withcode
field from 1.1.1.1.1.1.1.1.
$trim
- Trimcode
value.And with
{ multi: true }
for updating multiple documents.Sample Mongo Playground