0

I have an user object that looks like that

{
    "_id": ObjectId("string"),
    ...
    "clients": [
        {
            "_id": ObjectId("client1_string"),
            ...
        },
        {
            "_id": ObjectId("client2_string"),
            ...
        },
    ]
}

I wanna get this result

{
    "_id": ObjectId("client1_string"),
    ...
}

Anything I try returns me the user object that includes that client, but all I want is the client himself... what am I doing wrong? I have already tested couple of codes found from different questions and that is the last try which brings the same result.

users.findOne(
        { 
            '_id': ObjectId(user_id) 
        },
        {
            'clients': { $elemMatch: { '_id': ObjectId(client_id) } 
        }
})
daniel93
  • 145
  • 6
  • 1
    @whoami Thanks!! I took an example there and it helped me :) I forgot to add toArray and thought it doesn't work but once I added the result was fine. – daniel93 Apr 27 '20 at 21:37

1 Answers1

0

This worked for me (don't forget .toArray())

const result = await users.aggregate([
    { $match: { '_id': ObjectId(user_id) } },
    {
        $project: {
            clients: {
                $filter: {
                    input: '$clients',
                    as: 'client',
                    cond: { $eq: ['$$client._id', ObjectId(client_id)] }
                }
            }
        }
    }
]).toArray();
daniel93
  • 145
  • 6