简体   繁体   中英

How to use $lookup and $match against it in MongoDB aggregation?

I am having trouble with aggregation in Mongodb. I have a model User and UserExtra with extra details about the user. I need to do a $lookup to connect UserExtra to User output. But want to be able to filter results, based on age, gender and city, which are part of UserExtra. My current query is as follows, and it should return results but returs empty array.

    const match = {
        'userExtra.age': {
            $gt: dateTo.toISOString(),
            $lt: dateFrom.toISOString()
        },
        'userExtra.gender': gender
    }

    if (city) match['userExtra.city'] = city;

    const users = await User.aggregate([
        {
            $lookup: {
                from: 'user_extra',
                localField: 'userExtra',
                foreignField: '_id',
                as: 'userExtra'
            }
        },
        {
            $match: match
        },
        {
            $unwind: "$userExtra"
        }
    ]);

    res.send(users);

You have to unwind the lookup result first, then match pipeline.

let pipelineQuery = [
    {
        $lookup: {
            from: 'user_extra',
            localField: 'userExtra',
            foreignField: '_id',
            as: 'userExtra'
        }
    },
    {
        $unwind: "$userExtra"
    },
    {
        $match: match
    },
]

Hey guys I figured it out. I was using toIsoString() method, which turns the date into a string. All I did was remove the method and just passed the dateTo and dateFrom dates and now it works.

I would suggest testing each part of query one by one..First just run the lookup part in aggregate to see what the result looks like.After that run match.and subsequently add unwind.

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