javascript - 使用嵌套文档聚合 MongoDB 数组
问题描述
我正在尝试为我的 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
or$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",
}
},
}
}
},
])
推荐阅读
- java - 覆盖重复项而不是像 LinkedHashSet 那样忽略它们的 Android 用户对象队列?
- c++ - 模板参数排列顺序错误。这是正确的吗?
- javascript - 获取 Cookie Volume 并为 JavaScript 设置
- python - re.findall 返回单独的非重叠结果
- android - 单击后通知无法消失,并且 Notification setAutoCancel(true) 不起作用
- raspberry-pi - 如何在树莓派上安装 pandasdmx
- jquery - jquery 验证和 jquery ajax 插件表单提交
- r - 当我使用 as.numeric 时,我所有的纬度和经度都变为“1”
- hadoop - HBASE 与 HIVE:哪个更适合由多个字段唯一定义的数据?
- nuxt.js - Nuxt.js 在服务器目录中转译文件