1

I tried a few different answers in the forum but didn't help. The below is my query in which I have an issue with "project to filter" on $$this.star.email where star is an array.

   db.groups.aggregate([{
        $match: {
        _id: 162
        }
    }, {
        $addFields: {
        member: {
            $arrayElemAt: [{
            $filter: {
                input: "$members",
                cond: {
                $eq: ["$$this.email", '[email protected]']
                },
            }
            }, 0]
        }
        }
    }, {
        $project: {
        messages: {
            $filter: {
            input: "$messages",
            cond: {
            $and: [    
                {$gte: ["$$this.ts", "$member.added"]},
                {$eq : ["$$this.star.email",'5fbf1fb7b8d11a1f510e7f54' ]}
            ]
            }

            
            }

        }
        }
    }]).toArray()

my document looks like this. I want to filter messages having star with email "5fbf1fb7b8d11a1f510e7f54". The above query runs fine but does not yield the desired result.

{
    "_id" : 162,
    "messages" : [
        {
            "c" : "df64",
            "ts" : ISODate("2020-12-16T04:39:15.707Z"),
            "email" : "5fbf1fb7b8d11a1f510e7f54",
            "groupId" : 162,
            "s" : "s",
            "star" : [
                {
                    "email" : "5fbf1fb7b8d11a1f510e7f54",
                    "ts" : "2020-12-16T04:39:18.612Z"
                }
            ]
        },
        {
            "c" : "df64780ed694",
            "ts" : ISODate("2020-12-16T04:22:24.621Z"),
            "email" : "5fbf1fb7b8d11a1f510e7f54",
            "groupId" : 162,
            "s" : "s",
            "star" : [ ]
        }
    ]
}

1 Answer 1

1

The $$this.star.email will return array of email, You can use $in condition inside $filter condition,

cond: {
    $and: [
        { $gte: ["$$this.ts", "$member.added"] },
        { $in: ["5fbf1fb7b8d11a1f510e7f54", "$$this.star.email"] }
    ]
}

Playground

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.