更新MongoDB中的数组元素

发布于 2025-01-21 12:59:50 字数 476 浏览 2 评论 0原文

我正在尝试更新文档中的数组元素而不更改整个数组。

数组元素看起来像这样

“在此处输入图像描述”

假设我只需要更新索引1元素的值。为此,我有:

  1. _id

  2. 索引1的值

  3. ) 1650025534589.jpeg“)。

我认为MongoDB的arrayfilters可以对其进行更新,但我无法正确获取文档。 您的帮助将不胜感激。

I am trying to update an array element inside a document without changing whole array.

Array elements look like this

enter image description here

Suppose i have to only update index 1 element's value. For that i have:

  1. _id of the document

  2. index 1's value ("optionalImages-624476a7bd4d2bfe6bf86e9a-1-1650025533684.jpeg")

  3. to be updated value ("optionalImages-624476a7bd4d2bfe6bf86e9a-1-1650025534589.jpeg").

I think it can be updated by mongodb's arrayfilters but i don't get the documentation correctly.
Your help will be highly appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

祁梦 2025-01-28 12:59:50

QUERY1

  • ARRAYFILTERS使用$ [M]在路径内指定我们要更改
  • M的成员值是具有Value 20的成员,我们将其设置为100
    (而不是20和100,将您的“ .... jpg”字符串放置)
update(
{"_id": {"$eq": 1}},
{"$set": {"ar.$[m]": 100}},
{"arrayFilters": [{"m": {"$eq": 20}}])

query2

  • 管道更新> = mongodb 4.2
  • 使用阵列上的地图
  • 找到具有值20的成员,并用100

Playmongo

update(
{"_id": {"$eq": 1}},
[{"$set": 
   {"ar": 
     {"$map": 
       {"input": "$ar",
        "in": {"$cond": [{"$eq": ["$this", 20]}, 100, "$this"]}}}}}])

Query1

  • arrayFilters using $[m] inside the path to specify the member value that we want to change
  • m is the member with value 20, and we set it to 100
    (instead of 20 and 100, put your "....jpg" strings)

Playmongo

update(
{"_id": {"$eq": 1}},
{"$set": {"ar.$[m]": 100}},
{"arrayFilters": [{"m": {"$eq": 20}}])

Query2

  • pipeline update >= MongoDB 4.2
  • uses map on the array to
  • find the member with value 20, and replaces it with 100

Playmongo

update(
{"_id": {"$eq": 1}},
[{"$set": 
   {"ar": 
     {"$map": 
       {"input": "$ar",
        "in": {"$cond": [{"$eq": ["$this", 20]}, 100, "$this"]}}}}}])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文