Hi All,
I am looking for something equivalent of $elemMatch Query operator for use in $match within the Aggregation $lookup with pipeline. Any suggestions are welcome.
Thanks,
Sam
Hi All,
I am looking for something equivalent of $elemMatch Query operator for use in $match within the Aggregation $lookup with pipeline. Any suggestions are welcome.
Thanks,
Sam
You can use $elemMatch inside $lookup.pipeline.$match like this:
const pipeline = [
{
$lookup: {
from: 'other_collection',
pipeline: [
{
$match: {
itemsInArray: {
$elemMatch: {
foo: false,
bar: true,
},
},
},
},
],
as: 'result',
},
},
];
Though, it does not support pipeline variables
But you can add variable support with $unwind + $expr:
{
$lookup: {
from: 'other_collection',
let: {
foo: '$parentFoo',
bar: '$parentBar',
},
pipeline: [
{
$unwind: '$itemsInArray',
},
{
$match: {
$expr: {
$and: [
{ $eq: ['$itemsInArray.foo', '$$foo']},
{ $eq: ['$itemsInArray.bar', '$$bar']},
],
},
},
},
{
$group: {
_id: '$_id',
itemsInArray: {
$first: '$itemsInArray',
},
},
},
],
as: 'result',
},
},
];