Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

$addField with a condition in MongoDb

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) },
]);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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"
        ]
      }
    }
  }
])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading