Sample documents I created (based off the post-projection you provided):
/// documents with _id of 1, 2 and 6 have the same `memberOrgId` value
[
{
_id: 1,
name: 'Example Name 1',
memberOrgId: 'org1',
emailAddress: 'example1@email.com'
},
{
_id: 3,
name: 'Example Name 3',
memberOrgId: 'org3',
emailAddress: 'example3@email.com'
},
{
_id: 4,
name: 'Example Name 4',
memberOrgId: 'org4',
emailAddress: 'example4@email.com'
},
{
_id: 5,
name: 'Example Name 5',
memberOrgId: 'org5',
emailAddress: 'example5@email.com'
},
{
_id: 6,
name: 'Example Name 6',
memberOrgId: 'org1',
emailAddress: 'example6@email.com'
},
{
_id: 2,
name: 'Example Name 2',
memberOrgId: 'org1',
emailAddress: 'example2@email.com'
}
]
I’m not 100% sure of the expected output but does something like the below work?
Note: I only tested this on documents post-projection in my test environment. I do not know what the actual initial documents would look like.
I’m assuming currentUserId
and currentUserId
are known values since you use them in your initial $match
stage.
/// Get all members that have the matching orgId
{
$match: {
memberOrgId: 'org1'
}
},
/// using $project and $cond to display _id (member), memberOrgId, currentUser and targetUser (assuming _id values for currentUser and targetUser are known (1 and 2 in this case))
{
$project: {
_id:1,
memberOrgId:1,
currentUser : {
$cond: {
if : {$eq: ['$_id',1]},
then: '$$CURRENT',
else: '$$REMOVE'
}
},
targetUser : {
$cond: {
if : {$eq: ['$_id',2]},
then: '$$CURRENT',
else: '$$REMOVE'
}
}
}
},
/// $group all (assuming there is only 1 unique currentUser and 1 unique targetUser document)
{
$group: {
_id: null,
currentUser : {$max:'$currentUser'},
targetUser : {$max:'$targetUser'},
members : {$push:'$_id'}
}
}
Resulting in:
[
{
_id: null,
currentUser: {
_id: 1,
name: 'Example Name 1',
memberOrgId: 'org1',
emailAddress: 'example1@email.com'
},
targetUser: {
_id: 2,
name: 'Example Name 2',
memberOrgId: 'org1',
emailAddress: 'example2@email.com'
},
members: [ 1, 6, 2 ]
}
]
For reference, the $cond
documentation which may be of use.
If the above doesn’t suit your use case or requirements, please provide:
- use case details
- full aggregation in use currently
- 4-5 sample documents
- expected output based off the 4-5 sample documents
There might be a simpler way to achieve this but it’s difficult without any sample documents and without knowing the expected output.
I’d advise testing on a test environment to verify it suits your use case and/or requirement(s).
Regards,
Jason