skip to Main Content

Given that I have a hash subdocument within my document, how can I match a value – categoryId (itself added using $addFields) – to the sub-document key – categoryTypes – in my aggregation pipeline:
ex:

{
   _id: $someId,
   categoryId: 2,
   categoryTypes: {
     1: "hello world",
     2: "something else",
     3: "still more stuff"
   }
}

I need to match categoryId (2) to key in categoryTypes (2). In essence I need to say:

$match: { categoryId: categoryTypes }

Thanks!

2

Answers


  1. Chosen as BEST ANSWER

    Well it turns out that's simpler than I originally thought:

    1- First changed the hash into an array which produced a subdocument which looks like ARRAY: [ "0": {...}, "1": {...}, ...]

    // this is happening in $addFields stage
    categories: { "$objectToArray": "$categoryTypes"}
    

    2- Then in my project stage I did:

    category: {
        $filter: {
            input: '$categories',
            as: 'item',
            cond: {$eq: ['$$item.k', "$categoryId"]}
        }}
    

    Hope this helps others who may be looking for a similar solution.


  2. One option is to use $objectToArray:

    db.collection.aggregate([
      {$set: {allKeys: {$objectToArray: "$categoryTypes"}}},
      {$match: {$expr: {$in: [{$toString: "$categoryId"}, "$allKeys.k"]}}},
      {$unset: "allKeys"}
    ])
    

    See how it works on the playground example

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search