Arjan Singh Bal
Arjan Singh Bal

Reputation: 191

Mongo aggregation: add field derived from another field

I have documents of the following form present in a collection:

{
  name: "Michael",
  likes: [{ name: "reading", amount: 80}, {name: "eating", amount: 70}]
}

I want to add a new field to all the documents which will be 0/1 depending on whether the person likes reading. I have to check for the presence of likes.name = "reading". I tried adding the following stage in my aggregation pipeline to achieve this:

$addFields: {
  likes_reading: {
    $cond: {
      if: {
        $eq: ["$likes.name", "reading"]
      },
      then: 1,
      else: 0
    }
  }
}

However, $eq doesn't seem to be checking if "any" element of likes array has the required name, which is the kind of behaviour I've seen in many other places when we compare values with arrays. As a result all the likes_reading are set to 0. I need help setting this new field properly.

Upvotes: 3

Views: 3061

Answers (1)

Dheemanth Bhat
Dheemanth Bhat

Reputation: 4452

Since likes is an array you have to use $in operator so try this:

{
    $addFields: {
        likes_reading: {
            $cond: {
                if: { $in: ["reading", "$likes.name"] },
                then: 1,
                else: 0
            }
        }
    }
}

Or

{
    $addFields: {
        likes_reading: {
            $cond: [{ $in: ["reading", "$likes.name"] }, 1, 0]
        }
    }
}

Upvotes: 6

Related Questions