I am trying to query the company name and its admin users.
This is my structure:
companies: [
{
_id: "generatedComp1Id",
name: "abc",
users: [
{ _id: "...", user: "userId1", roles: ["admin"]},
{ _id: "...", user: "userId2", roles: ["user"]}
]
},
{
_id: "generatedComp2Id",
name: "xyz",
users: [
{ _id: "...", user: "userId3", roles: ["admin"]},
{ _id: "...", user: "userId4", roles: ["admin"]},
{ _id: "...", user: "userId5", roles: ["user"]}
]
}
]
I'm trying to query company name and admin users for each company given a companyId.
Output:
for company ID of generatedComp1Id:
{
name: "abc",
adminUsers: [
{user: "userId1"}
]
}
for company ID of generatedComp2Id:
{
name: "xyz",
adminUsers: [
{user: "userId3"},
{user: "userId4"}
]
}
I tried to do the next thing with no success:
[
{ $match: {_id: ObjectId("generatedComp1Id")}},
{
$project: {
name: 1,
adminUsers: {
$filter: {
input: "$roles",
as: "role",
cond: {
$eq: ["$$role", "admin"]
}
}
}
}
}
]
In addition, I tried unwind:
[
{$unwind:'$users'},
{$match:{'users.roles':{$in:['admin']}}},
{$group:{_id:'$_id',users:{$push:'$users'}}},
{ $project: { name: 1 } }
]
$filteruse the fieldusersinstead ofroles. And, in thecondcheck if theuser.roleshas the specific role.