I've got the following two Objects in a mongo collection named cars:
{vendor: "BMW",
model: "325i",
class: "coupe",
equipment: [
{name: "airbag",
cost: 120
},
{name: "led",
cost: 170
},
{name: "abs",
cost: 150
}
]
}
{vendor: "Mercedes",
model: "C 250",
class: "coupe",
equipment: [
{name: "airbag",
cost: 180
},
{name: "esp",
cost: 170
},
{name: "led",
cost: 120
}
]
}
I'm playing around with the new aggregation feature redact introduced in Mongo 2.6
I want to perform a query to get a list of cars with filtered equipment parts.
In words: Give me all cars of type coupe and only the information about LED and AIRBAG equipment.
I've tried this aggregations:
db.cars.aggregate(
[
{$match: {"class": "coupe"}},
{$redact:
{
$cond:
{
if: { $in : ["$name", ["airbag", "led"]]},
then: "$$DESCEND",
else: "$$PRUNE"
}
}
}
]
)
But that leads to following error:
assert: command failed: { "errmsg" : "exception: invalid operator '$in'", "code" : 15999, "ok" : 0 } : aggregate failed
What I'm doing wrong? Is there another way to achieve the goal.
I would expect to get back this result from Mongo:
{vendor: "BMW",
model: "325i",
class: "coupe",
equipment: [
{name: "airbag",
cost: 120
},
{name: "led",
cost: 170
}
]
}
{vendor: "Mercedes",
model: "C 250",
class: "coupe",
equipment: [
{name: "airbag",
cost: 180
},
{name: "led",
cost: 120
}
]
}
Any suggestions on how to achieve this?
Cheers, Ralf
$setIsSubsetinstead of$inwhen performing aggregations (including redaction) in MongoDB. See docs.mongodb.org/manual/reference/operator/aggregation/… - Paul$filterwith$infrom 3.4 version. Something likedb.cars.aggregate([ { "$match": { "class": "coupe", "equipment.name": { "$in": ["airbag", "led"] } } }, { "$addFields": { "equipment": { "$filter": { "input": "$equipment", "as": "equipment", "cond": { "$in": [ "$$equipment.name", ["airbag", "led"] ] } } } } } ])- s7vr