danspants
danspants

Reputation: 3417

MongoDB find documents with a matching field in another collection

    known = [{ system_id : 1234},
    { system_id : 1235},
    { system_id : 1236},
    { system_id : 1237}]

    peeps = [
{system_id: 1234, name : bob},
    {system_id: 1232, name : jim},
    {system_id: 1231, name : dave},
    {system_id: 1237, name : jeff}
]

If I have the above two collections, and I want to find documents in the peeps collection that have system_ids that exist in documents in the known collection, how can that be done? I'm currently running an aggregation across peeps where I find all the unique combinations of name and system_id, but I need to exclude anything that is not in the known collection.

Upvotes: 0

Views: 740

Answers (1)

pr0p
pr0p

Reputation: 2358

db.peeps.aggregate({
    $lookup : {
        from : "known",
        localField : "system_id",
        foreignField : "system_id",
        as : "someField"
    }
},{
    $match : {
        "someField.0" : {
            $exists : true
        }
    }
},{

    $project : {
        "someField" : 0
    }

})

This will output all those peeps which have system_id matched in knwon.

Upvotes: 3

Related Questions