0

I have a collection with a nested object array, I want to add a new boolean field to the document if the nested object array contains an item or not.

I could solve this by using map and in operators in two seperate addFields aggregation, but I wonder whether there is cleaner and smarter solution.

Sample Document:

[
  {
    "_id": "630875a5d0d70edb88e19a7b",
    "favorites": [
      {
        "_id": "6309ef9e538eef79c9e53827",
        "user": "6304d72e213e817ee090eb93",
        "recipe": "630875a5d0d70edb88e19a7b"
      },
      {
        "_id": "630f1b5a8f00dfa9a7a5006c",
        "user": "63066ce10722fdb443efb1f6",
        "recipe": "630875a5d0d70edb88e19a7b"
      }
    ]
  }
]

The solution I have:

db.collection.aggregate([
  {
    $addFields: {
      favoritedUserIds: {
        $map: {
          input: "$favorites",
          as: "favorited",
          in: "$$favorited.user"
        }
      }
    }
  },
  {
    $addFields: {
      isFavorited: {
        $in: [
          "6304d72e213e817ee090eb93", // user id
          "$favoritedUserIds"
        ]
      }
    }
  },
  {
    "$unset": "favoritedUserIds"
  }
])

Mongo Playground

1 Answer 1

2

You can just check whether the parameter is in favorites.user array.

db.collection.aggregate([
  {
    $addFields: {
      isFavorited: {
        $in: [
          "6304d72e213e817ee090eb93",
          "$favorites.user"
        ]
      }
    }
  }
])

Demo @ Mongo Playground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.