在MongoDB中,如何使用按当前值运行的函数更新嵌套文档的值?

发布于 2025-02-01 23:07:32 字数 465 浏览 3 评论 0原文

我正在尝试修剪嵌套文档中的字段价值,并且为了我的生命,我无法弄清楚如何使其正常工作。

我想在所有文档的代码字段上运行$ 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

暮年 2025-02-08 23:07:32

您可以工作使用聚合管道更新 for MongoDB版本4.2。

  1. $ 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}用于更新多个文档。

db.collection.update({},
[
  {
    $set: {
      products: {
        $map: {
          input: "$products",
          in: {
            $mergeObjects: [
              "$this",
              {
                code: {
                  $trim: {
                    input: "$this.code"
                  }
                }
              }
            ]
          }
        }
      }
    }
  }
],
{
  multi: true
})

示例mongo playground

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文