user2953680
user2953680

Reputation: 594

Mongoose find if some condition from other collection

I am trying to do the following Query in Mongo and I need some help. I have 2 collections:

collection 1 - users : {_id, name, lastname}

collection 2 - tutorial_finish : {user_id, completed}

i want to select all users where their name is "John Doe" and the user must not appear in collection2

Upvotes: 0

Views: 455

Answers (1)

mickl
mickl

Reputation: 49945

You can use $lookup to "join" the data from both collections and then $match to check if array created by $lookup is empty:

db.users.aggregate([
    {
        $match: { name: "John", lastname: "Doe" }
    },
    {
        $lookup: {
            from: "tutorial_finish",
            localField: "_id",
            foreignField: "user_id",
            as: "tutorials"
        }
    },
    {
        $match: { tutorials: [] }
    }
])

Upvotes: 1

Related Questions