简体   繁体   中英

MongoDB $lookup and $match object.key in foreign array

I am doing a $lookup to find 'events' where a customer is an attendee. The list of attendants is an array like this:

attendee: [{customer: <ID>}]

I tried this but it always returns an empty array:

$lookup: {
    from: "events",
    let: { customer: "$_id" },
    pipeline: [
        {
            $match: {
                $expr: {
                    $and: [
                        { $eq: ['$attendee.customer', '$$customer'] },
                    ]
                },
            }
        },
        { $limit: 1 },
        { $sort: {start: -1} },
        { $project: { id: "$_id", start: 1, end: 1, name: 1, host: 1 } },
    ],
    as: "event"
}

You are matching the fields on array so just replace $eq to $in

Your new code will be

$lookup: {
    from: "events",
    let: { customer: "$_id" },
    pipeline: [
        {
            $match: {
                $expr: {
            $in: [
                        "$attendee.customer",
                        "$$customer"
                    ]
                },
            }
        },
        { $limit: 1 },
        { $sort: {start: -1} },
        { $project: { id: "$_id", start: 1, end: 1, name: 1, host: 1 } },
    ],
    as: "event"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM