"只"取得符合條件的 Document 的 陣列元素
-
假設資料
```
{
"v": 1,
"flag":2,
"snacks":
[
{
"nutrients": [1,2,3],
"servings": 1,
"name": "coco"
},
{
"nutrients": [4,5,6],
"servings": 2,
"name": "yuyu"
}
]
},{
"v": 2,
"flag":3,
"snacks":
[
{
"nutrients": [9,8],
"servings": 1,
"name": "nick"
},
{
"nutrients": [4,5,6],
"servings": 2,
"name": "joe"
}
]
}```
我要如何"只"取得如下內容, 其餘欄位不要返回
{
"nutrients": [1,2,3],
"servings": 1,
"name": "coco"
}
-
因为snacks是一个数组,你要的是数组的每个元素都作为一个document返回回来吗?
```
db.collection.aggregate([
// {$match: ...} 推荐先过滤以减少要处理的数据量
{$unwind: "$snacks"},
{$project: {nutrients: "$snacks.nutrients", servings: "$snacks.servings", name: "$snacks.name"}}
]);```
-
我先前也有同樣的問題,感謝提問&解說~
-
解答了我新手的疑問,收藏不多說
-
如果
$match:{
v:1
},
{$unwind: "$snacks"},
則會返回
{
"nutrients": [1,2,3],
"servings": 1,
"name": "coco"
},
{
"nutrients": [4,5,6],
"servings": 2,
"name": "yuyu"
}可能我問題沒說清楚, 我還要過濾滿足 snacks.servings=1 的元素, 不滿足的不返回
如:
符合 v=1 的 snacks 有兩筆
"snacks":
[
{
"nutrients": [1,2,3],
"servings": 1,
"name": "coco"
},
{
"nutrients": [4,5,6],
"servings": 2,
"name": "yuyu"
}
]可是只要返回
{
"nutrients": [1,2,3],
"servings": 1,
"name": "coco"
},希望將返回的數據集縮到最小
-
借收藏一下 後續在使用上該會遇到很多類似的問題
-
db.collection.aggregate([
{$match: {v: 1, "snacks.servings": 1}},
{$unwind: "$snacks"},
{$match: {"snacks.servings": 1}},
{$project: {nutrients: "$snacks.nutrients", servings: "$snacks.servings", name: "$snacks.name"}}
]);aggregation的pipeline是可以多次重复出现的,但是这里只有第一个$match能够利用索引来加速。建议添加索引:
db.collection.createIndex({v: 1, "snacks.servings": 1})
更多关于aggregation的优化请参考文档:
本帖下載内容已隐藏,请登入以查看隐藏内容!
-
感謝... 所以關鍵在於使用 $match 逐層過濾..