0

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!

1 Answer 1

1
  • $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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.