问题
I have a collection that looks something like:
[
{
"_id": 1,
"title": "dummy title",
"settings": [
{
"type": "light",
"status": "enabled"
},
{
"type": "flare",
"status": "disabled"
},
{
"type": "toolbar",
"status": "enabled"
}
]
}
]
I wanna fetch it by Id but only with the "enabled" settings and not sure how the aggregation pipeline should look like.
I supposed to create the query using mongoTemplate in Java / Kotlin but even just the mongo query would be enough.
回答1:
You can do it with a $filter
db.collection.aggregate([
{
$project: {
_id: 1,
title: 1,
settings: {
$filter: {
input: "$settings",
as: "item",
cond: {
$eq: [
"$$item.status",
"enabled"
]
}
}
}
}
}
])
try it here
回答2:
//working code from MongoDB shell/CLI version 4.26(on windows 10 machine/OS)
> db.titles.find().pretty();
{
"_id" : 1,
"title" : "dummy title",
"settings" : [
{
"type" : "light",
"status" : "enabled"
},
{
"type" : "flare",
"status" : "disabled"
},
{
"type" : "toolbar",
"status" : "enabled"
}
]
}
> db.titles.aggregate([
... {$unwind:"$settings"},
... {$match:{"settings.status":"enabled"}}
... ]);
{ "_id" : 1, "title" : "dummy title", "settings" : { "type" : "light", "status" : "enabled" } }
{ "_id" : 1, "title" : "dummy title", "settings" : { "type" : "toolbar", "status" : "enabled" } }
> print("MongoDB: ",db.version());
MongoDB: 4.2.6
>
来源:https://stackoverflow.com/questions/64306166/mongodb-filter-nested-array