javapedia.net
javapedia.net

Reputation: 2731

Mongodb aggregate query project on Array of Arrays

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" : [ ]
        }
    ]
}

Upvotes: 1

Views: 229

Answers (1)

turivishal
turivishal

Reputation: 36134

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

Upvotes: 1

Related Questions