【问题标题】:MongoDB pipeline $unset field if id is in array如果 id 在数组中,则 MongoDB 管道 $unset 字段
【发布时间】:2020-11-21 07:11:20
【问题描述】:

鉴于下面的条目列表,如果 _id 在 myArray 中,我想在管道阶段 $unset platformA。

const myArray = ['5f22f9ac6ee02a6707cf0586']

db.profiles.findOne({_id: ObjectId("5f22f9ac6ee02a6707cf0586")})

{
    "_id" : ObjectId("5f22f9ac6ee02a6707cf0586"),
    "platformA" : {
        ...
    },
    "platformB": {
        ...
    }
}

这样项目之后的结果就是

{
    "_id" : ObjectId("5f22f9ac6ee02a6707cf0586")
    "platformB": {
        ...
    }
}

我不明白如何访问 $_id 字段并有条件地将 $project platformA 设置为 0(如果它不在 myArray 中)。

{
    // only show platformA when not in myArray
    $project: {
      platformA: 0
    }
  },

【问题讨论】:

标签: mongodb mongoose


【解决方案1】:

终于想通了。

{
  // only show platformA when id is not in myArray
  $project: {
    platformA: {
      $cond: [{$setIsSubset: [['$_id'], myArray]}, 0, 1 ] }
    }
  }
},
{
  $match: {
    $and: [{
      platformA: {$ne: 0}
    }, {
      platformB: {$ne: 0}
    }]
  }
}

【讨论】:

    【解决方案2】:

    @user3586358,如果您对它感到满意,可以回答您自己的问题,但我已经准备了一些研究,因此被嘲笑向您展示,可能对其他人有帮助,

    假设这是 ids 数组,

    let myArray = [1,2,3];
    

    与 find() 一起使用

    • 使用$cond$in
    db.collection.find(
    {},
    {
      _id: 1,
      name: 1,
      platformB: 1,
      platformA: {
        $cond: [
          {$in: ["$_id", myArray]},
          0,
          "$platformA"
        ]
      }
    })
    

    工作场所:https://mongoplayground.net/p/OgvD_V0qn_H

    与聚合()一起使用

    db.collection.aggregate([
      {
        $project: {
          _id: 1,
          name: 1,
          platformB: 1,
          platformA: {
            $cond: [
              {$in: ["$_id", myArray]},
              0,
              "$platformA"
            ]
          }
        }
      }
    ])
    

    工作场所:https://mongoplayground.net/p/753MKWPUJmC

    【讨论】:

      猜你喜欢
      • 2019-02-13
      • 2020-09-23
      • 2015-12-17
      • 2021-12-02
      • 1970-01-01
      • 2021-11-11
      • 1970-01-01
      • 1970-01-01
      • 2017-02-12
      相关资源
      最近更新 更多