Reputation: 5777
I'm trying to perform a $lookup
using two fields on MongoDB 3.6. I've already read the docs and similar questions here, but I was unable to find what's wrong.
Collection acls
:
[ { _id: 1, FolderId: 4, Sid: 'S-123-456' }
{ _id: 2, FolderId: 5, Sid: 'S-234-567' }
{ _id: 3, FolderId: 6, Sid: 'S-345-678' } ]
Collection groups
:
[ { _id: 1, ProcessId: 10, Sid: 'S-123-456', Users: [ 'user1', 'user2'] }
{ _id: 2, ProcessId: 10, Sid: 'S-234-567', Users: [ 'user1'] }
{ _id: 3, ProcessId: 20, Sid: 'S-123-456', Users: [ 'user2'] } ]
Query:
db.acls.aggregate({
$lookup:
{
from: 'groups',
let: { 'ProcessId': 10, 'GroupSid': '$Sid' },
pipeline: [{
$match: {
$expr: {
$and: [
{
$eq: [ '$ProcessId', '$$ProcessId' ]
},
{
$eq: [ '$Sid', '$$GroupSid' ]
}
]
}
}
}],
as: 'grouplist'
}
})
I was expecting to return something like:
{ _id: 1, FolderId: 4, Sid: 'S-123-456',
grouplist: [ { _id: 1, ProcessId: 10, Sid: 'S-123-456', Users: [ 'user1', 'user2'] }] }
but instead I'm getting 'Script executed successfully, but there are no results to show'
, on Robo 3T.
Upvotes: 1
Views: 801
Reputation: 3845
db.getCollection("acls").aggregate(
// Pipeline
[
// Stage 1
{
$lookup: // Equality Match
{
from: "groups",
localField: "Sid",
foreignField: "Sid",
as: "grouplist"
}
},
// Stage 2
{
$project: {
grouplist: {
$filter: {
input: "$grouplist",
as: "group",
cond: {
$eq: ["$$group.ProcessId", 10]
}
}
},
FolderId: 1,
Sid: 1
}
},
]
);
Upvotes: 0
Reputation: 46481
$let
variable operator must start with the lower case letter.
db.acls.aggregate([
{ "$lookup": {
"from": 'groups',
"let": { "groupSid": "$Sid" },
"pipeline": [
{ "$match": {
"$expr": { "$eq": [ "$Sid", "$$groupSid" ] },
"ProcessId": 10
}}
],
"as": "grouplist"
}}
])
Upvotes: 1
Reputation: 787
Try This it's working fine. Your let keyword must be start with lowercase
db.acls.aggregate([
{
$lookup:
{
from: "groups",
let: { processid: 10, sid: "$Sid" },
pipeline: [
{ $match:
{ $expr:
{ $and:
[
{ $eq: [ "$ProcessId", "$$processid" ] },
{ $gte: [ "$Sid", "$$sid" ] }
]
}
}
}
],
as: "grouplist"
}
}
])
Upvotes: 1