mkimmet
mkimmet

Reputation: 769

Lookup object in nested array based on another property in mongodb aggregation

I want to do a lookup using the ObjectId in thing.subCategory on the nested category.subCategories array to find the corresponding object in that array.

I have an aggregation that currently generates this:

{
  _id: ObjectId("...")
  thing: {
     category: ObjectId("001"),
     subCategory: ObjectId("123")
  },
  category: {
     id: ObjectId("001"),
     title: "Some Category",
     subCategories: [
       {
          _id: ObjectId("123"),
          title: "Some Subcategory I want"
       },
       {
          _id: ObjectId("124"),
          title: "another subcategory"
       }
      ]
   }
}

And I want to get to:

   {
      _id: ObjectId("...")
      thing: {
         category: ObjectId("001"),
         subCategory: ObjectId("123")
      },
      category: {
         id: ObjectId("001"),
         title: "Some Category",
         subCategories: [...]
       },
      subCategory: 
      {
          _id: ObjectId("123"),
          title: "Some Subcategory I want"
      }
    }

Thanks for any help!

Upvotes: 0

Views: 27

Answers (1)

turivishal
turivishal

Reputation: 36104

  • $filter to iterate loop of category.subCategories and filter matching category
  • $arrayElemAt to get first element from filtered category
db.collection.aggregate([
  {
    $addFields: {
      subCategory: {
        $arrayElemAt: [
          {
            $filter: {
              input: "$category.subCategories",
              cond: { $eq: ["$$this._id", "$thing.category"] }
            }
          },
          0
        ]
      }
    }
  }
])

Playground

Upvotes: 1

Related Questions