1

I have collections of the following structure:

objects:

[{"type": "someTypeOne", "menuId": 1},
{"type": "someTypeTwo", "menuId": 1},
{"type": "someTypeOne", "menuId": 2}]

menus:

[{"id":1, "type": "someTypeOne"},
{"id":2, "type": "someTypeOne"}]

I need to find all objects where "type" property doesn't match its menus "type". In this case the desired output would be:

[{"type": "someTypeTwo", "menuId": 1}]

I think that I should use aggregation for this one and I'm fiddling with it at the moment but I was not able to formulate a working query so far. Thanks

1 Answer 1

2

You can try below aggregation:

db.objects.aggregate([
    {
        $lookup: {
            from: "menus",
            localField: "menuId",
            foreignField: "id",
            as: "menu"
        }
    },
    {
        $unwind: "$menu"
    },
    {
        $match: {
            $expr: {
                $ne: [ "$menu.type", "$type" ]
            }
        }
    },
    {
        $project: {
            menu: 0
        }
    }
])

$lookup allows you to get data from both collections, then you can run $unwind on menu array to get single menu per document and you can apply you inequality condition using $match and $expr

Mongo Playground

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

1 Comment

@FIIFE cause it's extremely easy to answer when you clearly define what you need (by examples)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.