Home > Blockchain >  $addField with a condition in MongoDb
$addField with a condition in MongoDb

Time:11-15

I have a query and I want when fullname field exist to add a field called type with a value of 'Users' and when there is name instead of fullname I want to add type field with value 'POSTS'

Here is my implementation, but its not working:

const result = await User.aggregate([
  {
    $unionWith: "recipes",
  },
  {
    $match: {
      $or: [
        {
          fullname: { $regex: query, $options: "i" },
        },
        {
          username: { $regex: query, $options: "i" },
        },
        {
          name: {
            $regex: query,
            $options: "i",
          },
        },
      ],
    },
  },
  { $project: { _id: 1, fullname: 1, name: 1 } },
  {
    $addFields: {
      type: {
        $cond: [
          {
            $exist: "fullname",
          },
          "POSTS",
          "USERS",
        ],
      },
    },
  },
  { $skip: parseInt(skip) },
  { $limit: parseInt(limit) },
]);

CodePudding user response:

The problem was that we don't have $exist aggregate operator, so we do it using the $type operator (exist query operator cannot be used in aggregation, outside of a match)

Query1

  • you can use this if you want if fullname to have a false value(like null, missing,false) to get USERS type

Test code here

db.collection.aggregate([
  {
    "$set": {
      "type": {
        "$cond": [
          "$fullname",
          "USERS",
          "POSTS"
        ]
      }
    }
  }
])

Query2

  • you can use this if you want this only when field is missing

Test code here

db.collection.aggregate([
  {
    "$set": {
      "type": {
        "$cond": [
          {
            "$eq": [
              {
                "$type": "$fullname"
              },
              "missing"
            ]
          },
          "POSTS",
          "USERS"
        ]
      }
    }
  }
])
  • Related