I have the following document structure on my mongodb collection:
{
"_id" : "5Ci9sLeBu2iPbWtR5",
"productId" : "010101111",
"description" : "PRODUCT EXAMPLE REF 1001",
"prices" : [
{
"priceId" : 10,
"description" : "Promotions",
"price" : 97.99
},
{
"priceId" : 15,
"description" : "Retail list",
"price" : 105.65
},
{
"priceId" : 20,
"description" : "Standard list",
"price" : 109.10
}
]}
What I want is query only specific array of priceIds, for example: [10,20], resulting:
{
"_id" : "5Ci9sLeBu2iPbWtR5",
"productId" : "010101111",
"description" : "PRODUCT EXAMPLE REF 1001",
"prices" : [
{
"priceId" : 10,
"description" : "Promotions",
"price" : 97.99
},
{
"priceId" : 20,
"description" : "Standard list",
"price" : 109.10
}
]}
Using $in operator with $filter like this (the perfect imaginary scenario):
db.getCollection('products').aggregate([
{$match: { "productId":"010101111" }},
{$project: {
"prices": {
$filter: {
input: "$prices",
as: "price",
cond: { $in: ["$$price.priceId",[10, 20]] }
}
}
}}])
it doesn't work, because mongodb complains about $in operator ("invalid operator '$in'").
Of course, I can do that with $unwind, but I'll have a performance problem, because I need to group again after all.
The closest answers I've found for my question were these two:
- Retrieve only the queried element in an object array in MongoDB collection
- Filter array using the $in operator in the $project stage
but none of them were about searching with array filter in subdocuments.