问题
I have 2 collections :
Users collection :
{
_id: ObjectId
}
Toto Collection :
{
_id: ObjectId
fieldA: {_id: ObjectId}
fieldB: [{_id: ObjectId}, {_id: ObjectId}]
}
And I'm trying to join the element of A collection which fieldA's id OR one of fieldB's id is matching with user's id with following aggregation :
db.users.aggregate([
{
$lookup: {
from: "Toto",
let: { "user_id": "$_id" },
as: "fcollection",
pipeline: [
{ $match:
{$or:[
{"fieldB": {$elemMatch: {"_id": "$$user_id"}}},
{$expr: {$eq :["$fieldA._id", "$$user_id"]}}
]}
}
]
}
])
But in the output I'm just getting the document's where fieldA's id is matching but none of the fieldB's. What am I doing wrong?
回答1:
You need to use $in aggregation pipeline operator to check an element exists in an array :
db.users.aggregate([
{
$lookup: {
from: "Toto",
let: {
"user_id": "$_id"
},
as: "fcollection",
pipeline: [
{
$match: {
$or: [
{
$expr: {
$in: [
"$$user_id",
"$fieldB._id"
]
}
},
{
$expr: {
$eq: [
"$fieldA._id",
"$$user_id"
]
}
}
]
}
}
]
}
}
])
Test : MongoDB-Playground
来源:https://stackoverflow.com/questions/60550548/mongodb-aggregation-or-with-elemmatch-expr-inside-lookup-pipeline