[英]aggregate MongoDB array with nested documents
I am trying to make a consultant on my MongoDB database:我正在尝试为我的 MongoDB 数据库做一名顾问:
What I want to do is to obtain some data that is integrated in a nested array and filter by one of this nested keys.我想要做的是获取一些集成在嵌套数组中的数据,并按此嵌套键之一进行过滤。
The document is the following:文件如下:
[
{
"name": "PharmaMaria",
"country": "Spain",
"currency": "EUR",
"medicines": [
{
"name": "Medicine 1",
"type": "Suncream",
"price": 32,
},
{
"name": "Medicine 2",
"type": "Suncream",
"price": 5
},
{
"name": "Medicine 3",
"type": "Pills",
"price": 7
}
]
}
]
And I want to get something like this filtering by medicines.type
我想通过
medicines.type
过滤类似的东西
values = [
{
"name": "Medicine 1",
"price": 32
},
{
"name": "Medicine 2",
"price": 5
}
]
Here is the playground I created https://mongoplayground.net/p/_riatO8PKVp这是我创建的游乐场https://mongoplayground.net/p/_riatO8PKVp
Thanks!谢谢!
You have to add a $project
or $addFields
stage and use $filter
operator to apply the condition on each elements.您必须添加
$project
或$addFields
阶段并使用$filter
运算符将条件应用于每个元素。
db.collection.aggregate([
{
"$match": {
"country": "Spain",
"medicines.type": "Suncream"
},
},
{
"$addFields": { // <- To add a new key
"medicines": { // <- Replacing existing `medicines` key
"$filter": { // <- Apply condition on each array elements
"input": "$medicines",
"as": "elem",
"cond": { // <- Applying match condition inside this block
"$eq": [
"$$elem.type",
"Suncream"
],
}
}
}
}
},
])
To get Only specific keys from array, use $map
要仅从数组中获取特定键,请使用
$map
db.collection.aggregate([
{
"$match": {
"country": "Spain",
"medicines.type": "Suncream"
},
},
{
"$addFields": {
"medicines": {
"$map": {
"input": {
"$filter": {
"input": "$medicines",
"as": "elem",
"cond": {
"$eq": [
"$$elem.type",
"Suncream"
],
}
}
},
"as": "med",
"in": {
"name": "$$med.name",
"price": "$$med.price",
}
},
}
}
},
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.