【问题标题】:Updating Subdocument Array in PHP Mongo在 PHP Mongo 中更新子文档数组
【发布时间】:2021-10-08 12:43:37
【问题描述】:

我正在尝试更新 PHP Mongo 中的子文档数组

$result = $collection->updateMany(
    [
        '_id' => new MongoDB\BSON\ObjectID('61613dcd437b996bc227ffe2'),
        'messages.type' => 'test'
    ],
    ['$set' => ['messages.$[m].direction' => '999']],
    [
      'multi' => true,
      'arrayFilters' => [['m.type'=> 'test']]
    ]

);

####更新。我的数组是

[{"_id":{"$oid":"6163f2c9fc197a54f03ca8c8"},"id":7,},"messages":{"1":{"type":"1","time": "19.04.2020 09:14:42","message":"这是 testmsg"}},"ssg":"ruther"}]

另外,如何使用索引 1、2、3.. 等更新整个子文档?

【问题讨论】:

标签: mongodb php-mongodb


【解决方案1】:

使用$[]arrayFilters

db.collection.update({
  "_id": ObjectId("61603458c08ad41af13bf352"),
  "messages.type": "05.04.2020 03:27:23"
},
{
  $set: {
    "messages.$[m].direction": "999"
  }
},
{
  multi: true,
  arrayFilters: [
    {
      "m.type": "05.04.2020 03:27:23"
    }
  ]
})

更新

如果你想用新的替换单个消息数组

$set: {
    "messages.$[m]": {
      "type": "02.06.2020 19:27:23",
      "message": "This is a 3 Msg",
      "direction": "0"
    }
  }

mongoplayground

【讨论】:

  • 但是将_id 与messages.type 一起使用是不可取的。如果我与 _id 结合可以吗?
  • 另外,如何更新整个子文档?即我想用新的替换那个单一的消息数组(而不是替换单一类型的列)
  • 当然可以,我更新我的答案。
  • 嗨,@YuTing。你的查询工作。但你能帮忙吗?我如何处理子文档数组 "messages":{"1":{"type":"notes","time":"19.04.2020 09:14:42","message":"fakemsg","direction" :"0"}}
  • 如何使用索引 1、2、3 更新整个子文档。等等。请检查我的问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-02
  • 2019-07-04
  • 1970-01-01
  • 2014-01-28
  • 1970-01-01
  • 2021-04-23
  • 2021-07-20
相关资源
最近更新 更多