我正在嘗試為我的 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
謝謝!
uj5u.com熱心網友回復:
您必須添加一個$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 執行
Mongo Playground 示例執行
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/340239.html
標籤:javascript 节点.js 数组 MongoDB 文档
下一篇:如何過濾mongodb中的檔案?
