繁体   English   中英

如果数组中存在文档字段值之一,则更新集合中的文档

[英]Update documents in a collection if one of the document field value exists in array

我有一个带有collection1collection1Column和另一列presentInArray1

--------------------------------------------
| collection1Column | presentInArray1      |
--------------------------------------------
| A                 | null                 |
| B                 | null                 |
| C                 | null                 |
| D                 | null                 |
| E                 | null                 |
--------------------------------------------

我有一个这样的array1

let array1 = ['A', 'C', 'D'];

现在,仅当在array1中找到与collection1Column完全匹配时,我才需要更新collection1的列presentInArray1 在给出的示例中 - 匹配项是ACD

我认为一种可能的 javascript 解决方案如下:

  • 从集合和数组中获取所有值。

  • 一旦这些值可用,就从collection1collection1Column中一个一个地获取值,并在array1上迭代以找到匹配项。

  • 一旦找到匹配项,将用true更新presentInArray1

在这种情况下 - 如果array1中存在文档字段collection1Column值之一,我如何更新集合collection1中的文档?

另外,这是我迄今为止尝试过的代码:

collection1.update({
    'collection1Column': {
      $in: array1
    }
  }, {
    $set: {
      'presentInArray1': true
    }
  }, {
    multi: true
  },
  function(err, result) {
    if (err) throw err;
  });

这似乎也不起作用。 我不确定为什么:

{"result":{"n":217,"nModified":0,"opTime":{"ts":"6833283007906840577","t":13},"electionId":"7fffffff000000000000000d","ok":1,"$clusterTime":{"clusterTime":"6833283007906840577","signature":{"hash":"W1KNoy0a9d2iTU3OiIa2jlc4y00=","keyId":"6803936209337843714"}},"operationTime":"6833283007906840577"},"connection":{"id":5,"host":"cluster0-shard-00-01-foobar.mongodb.net","port":27017},"modifiedCount":0,"upsertedId":null,"upsertedCount":0,"matchedCount":217,"n":217,"nModified":0,"opTime":{"ts":"6833283007906840577","t":13},"electionId":"7fffffff000000000000000d","ok":1,"$clusterTime":{"clusterTime":"6833283007906840577","signature":{"hash":"W1KNoy0a9d2iTU3OiIa2jlc4y00=","keyId":"6803936209337843714"}},"operationTime":"6833283007906840577"}

就 memory 和性能而言,这看起来非常昂贵。

请建议!

简单来说,如何在MongoDB中进行V 查找

MongoDB 服务器版本:4.2.6

collection1.update({
    'array1': $collection1Column
  }, {
    $set: {
      'presentInArray1': true
    }
  }, {
    multi: true
  },
  function(err, result) {
    if (err) throw err;
  });

假设collection1Column不是数组类型

如果该字段包含一个数组,则 $in 运算符选择其字段包含一个数组的文档,该数组包含至少一个与指定数组中的值匹配的元素(例如,等)

更多详情: https://docs.mongodb.com/manual/reference/operator/query/in/

我使用updateMany而不是update并且它有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM