我想让我的MongoDB数据库顾问:
我想做的是获取一些数据,这些数据集成在一个嵌套数组中,并通过这个嵌套键之一进行筛选。
文件内容如下:
[
{
"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
}
]
}
]
我想通过medicines.type
values = [
{
"name": "Medicine 1",
"price": 32
},
{
"name": "Medicine 2",
"price": 5
}
]
这是我创建的游乐场https://mongoplayground.net/p/_riatO8PKVp
谢谢!
您必须添加$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"
],
}
}
}
}
},
])
使用$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",
}
},
}
}
},
])
上面的Mongo Execution示例
Mongo Playground Sample Execution