Home > Software design >  Add new field based on nested array object
Add new field based on nested array object

Time:09-02

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

CodePudding user response:

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

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

Demo @ Mongo Playground

  • Related