Home > database >  In MongoDB, how do I update the value of a nested document using a function that operates on the cur
In MongoDB, how do I update the value of a nested document using a function that operates on the cur

Time:05-27

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.

  1. $set - Set products field value.

    1.1. $map - Iterate the products array and return a new array.

    1.1.1. $mergeObjects - Merge current object ($$this) and object with code field from 1.1.1.1.

    1.1.1.1. $trim - Trim code value.

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
})

Sample Mongo Playground

  • Related