簡體   English   中英

Mongoose 用 $or 條件更新文檔

[英]Mongoose update document with $or condition

我想搜索具有相同action_object.reply.idaction_target.reply.id的所有活動。 是這樣的:

Activity
  .find({ $or: [
    { 'action_object.reply.id': replyId }, 
    { 'action_target.reply.id': replyId }
  ]});

但我也只想像這樣更新已removed的屬性:

Activity
  .update({ 'action_object.reply.id': replyId }, {
            'action_object.reply.removed': true }, { multi: true });

Activity
      .update({ 'action_target.reply.id': replyId }, {
                'action_target.reply.removed': true }, { multi: true });

是否有可能以某種方式組合這兩個查詢? 我想更新action_target.reply.removed where action_target.reply.idaction_object.reply.removed where action_object.reply.id

或者我必須像上面那樣為此寫兩個不同的查詢。

update調用的第一個參數是查詢對象,因此您可以簡單地使用相同的$ or查詢。 Mongo將更新查詢檢索的所有文檔。

Activity
  .update({ $or: [
    { 'action_object.reply.id': replyId }, 
    { 'action_target.reply.id': replyId }
  ]}, {'action_object.reply.removed': true }, { multi: true });

在 4.2 中,您可以使用$cond

// Configuration
[
  {
    "action_object": {
      "reply": {
        "id": "bar",
        "removed": false
      }
    }
  },
  {
    "action_target": {
      "reply": {
        "id": "foo",
        "removed": false
      }
    }
  }
]

// Query
db.collection.update({
  $or: [
    {
      "action_object.reply.id": "foo"
    },
    {
      "action_target.reply.id": "foo"
    }
  ]
},
[
  {
    $set: {
      "action_object.reply.removed": {
        $cond: [
          {
            $eq: [
              "foo",
              "$action_object.reply.id"
            ]
          },
          true,
          "$$REMOVE"
        ]
      },
      "action_target.reply.removed": {
        $cond: [
          {
            $eq: [
              "foo",
              "$action_target.reply.id"
            ]
          },
          true,
          "$$REMOVE"
        ]
      }
    }
  }
],
{
  multi: true
})

https://mongoplayground.net/p/tOLh5YKRVX1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM