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"
}
]
}
CodePudding user response:
You can work the Updates with Aggregation Pipeline for MongoDB version 4.2.
$set- Setproductsfield value.1.1.
$map- Iterate theproductsarray and return a new array.1.1.1.
$mergeObjects- Merge current object ($$this) and object withcodefield from 1.1.1.1.1.1.1.1.
$trim- Trimcodevalue.
And with { multi: true } for updating multiple documents.
db.collection.update({},
[
{
$set: {
products: {
$map: {
input: "$products",
in: {
$mergeObjects: [
"$$this",
{
code: {
$trim: {
input: "$$this.code"
}
}
}
]
}
}
}
}
}
],
{
multi: true
})
