如何使用投影僅查看集合的所有檔案中的以下部分?
條件:我只需要獲取“type”:“DEBIT”和以下 2 行,而不是相同型別的所有其他鍵。我不想查看其他型別,如帳戶、存款。
{
"key": "Call",
"enabled": true,
}
我在以下結構中擁有的示例檔案。
{
"_id": "1",
"menu": [
{
"type": "ACCOUNT",
"scope": "ACCOUNT",
"items": [
{
"key": "Call",
"enabled": true,
},
{
"key": "Work",
"enabled": true,
}
]
},
{
"type": "DEPOSIT",
"scope": "DEPOSIT",
"items": [
{
"key": "Call",
"enabled": true,
},
{
"key": "Work",
"enabled": true,
}
]
},
{
"type": "DEBIT",
"scope": "DEBIT",
"items": [
{
"key": "Call",
"enabled": true,
},
{
"key": "Work",
"enabled": true,
}
]
},
]
}
uj5u.com熱心網友回復:
首先,您需要到$unwind選單然后 $match 型別借方和過濾陣列項,然后分組以創建最終結果
db.collection.aggregate([
{
"$unwind": "$menu"
},
{
$match: {
"menu.type": "DEBIT"
}
},
{
"$project": {
_id: 1,
"menu.items": {
"$filter": {
"input": "$menu.items",
"as": "s",
"cond": {
$and: [
{
$eq: [
"$$s.enabled",
true
]
},
{
$eq: [
"$$s.key",
"Call"
]
}
]
}
}
}
}
},
{
"$group": {
"_id": "$_id",
"menu": {
"$push": "$menu"
}
}
}
])
https://mongoplayground.net/p/kRChgF9rLsI
uj5u.com熱心網友回復:
用 $filter
db.collection.aggregate([
{
"$match": {
"menu.type": "DEBIT"
}
},
{
"$set": {
"menu": {
"$filter": {
"input": "$menu",
"as": "m",
"cond": {
$eq: [
"$$m.type",
"DEBIT"
]
}
}
}
}
}
])
mongoplayground
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/345424.html
標籤:数组 MongoDB 猫鼬 mongodb-查询 皮蒙戈
