MongoDB pipeline $unset field if id is in array

Viewed 70

Given a list of entries like the ones below, I want to $unset platformA in a pipeline stage if the _id is in myArray.

const myArray = ['5f22f9ac6ee02a6707cf0586']

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

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

So that after the project the result is

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

I dont understand how I can access the $_id field and conditionally $project platformA to 0 if it is not in myArray.

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

Finally figured it out how to do it.

{
  // 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}
    }]
  }
}

@user3586358, Its good to answer your own question if you satisfied with it then its ok, but i have already prepared some research on this so derided to show you, may be its helpful to others,

Assume this is ids array,

let myArray = [1,2,3];

use with find()

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

Working Playground: https://mongoplayground.net/p/OgvD_V0qn_H

use with aggregate()

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

Working Playground: https://mongoplayground.net/p/753MKWPUJmC

Related