【问题标题】:mongo operator to update all matching items in an arraymongodb 运算符更新数组中的所有匹配项
【发布时间】:2019-05-13 01:23:05
【问题描述】:
messages: [
    {
        user: "5c57c85a9354fa24ad749137",
        text: "hello",
        unread: true
    },
    {
        user: "5c57c85a9354fa24ad749137",
        text: "world",
        unread: true
    }
]

我正在尝试使用 $[] 更新 id 与给定 id 不匹配但没有任何反应的所有数组元素

ChatSchema.update(
        {_id: mongoose.Types.ObjectId(req.body.conversationId), "messages": {$elemMatch: {"user": {$ne: mongoose.Types.ObjectId(req.body.userId)}}}},
        {$set: {"messages.$[].unread": false}},
        {multi: true}
        ).exec()

当我使用单个 $ 运算符时,它只会更新找到的第一个元素。

我正在使用 mongo 4.0.6 版和 mongoose 6.7.0 版

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    匹配条件应该是$[identifier]

    ChatSchema.update(
      { "_id": mongoose.Types.ObjectId(req.body.conversationId) }},
      { "$set": { "messages.$[msg].unread": false }},
      { "arrayFilters":[{ "msg.user": { "$ne": mongoose.Types.ObjectId(req.body.userId) }}] }
    )
    

    【讨论】:

    • 我试过了,结果一样,没有任何反应
    • 去掉$ne操作符,检查是否有效,然后添加$ne
    • 不,不管有没有 $ne 运算符,它都不会更新,但是当我使用单个 $ 而不是 $[msg] 时它会更新,问题是它只更新第一个匹配项
    • @I'mnothuman 运行这个命令db.adminCommand( { setFeatureCompatibilityVersion: "3.4" })
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-25
    相关资源
    最近更新 更多