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

Add new field based on nested array object

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:

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

[
  {
    "_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

>Solution :

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

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

Demo @ Mongo Playground

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