7

I have two collections, products and properties.

I'm doing a lookup such as:

[{
        $match: {
            category_id: mongoose.Types.ObjectId(category_id)
        }
    },
    {
        $lookup: {
            from: "properties",
            localField: "category_id",
            foreignField: "category_id",
            as: "properties"
        }
    }
]

This is basically getting me all of the products that match the category_id and including the properties that match the same category_id.

I need to add an additional check, for some_id on the properties result. In otherwords, the properties should be grouped by the some_id that is returned from the products collection and matches the same key in properties. Does that make sense? Basically having the ability to have multiple local/foreign field definitions.

any idea how I could this?

2
  • 1
    Any sample data available? Like input data and then desired output. Commented Sep 8, 2017 at 19:13
  • Have you tried $filter ? Something like { $addFields: { properties: { $filter: { input: "$properties", as: "result", cond: { $eq: ["$$result.some_id ", "$some_id"] } } } } } Commented Sep 8, 2017 at 20:30

1 Answer 1

6

Since version 3.6 we can use uncorrelated sub-queries

    {
       $lookup:
         {
           from: '<collection to join>',
           let: { <var_1>: '<expression>', …, <var_n>: '<expression>' },
           pipeline: [ '<pipeline to execute on the collection to join>' ],
           as: <output array field>
         }
    }

This allows us to to have more than a single equality match on the lookup. See also: https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.