[英]How to fetch data from nested json in mongodb when key is not known(variable)
我如何獲取已實現目標的用戶列表,即目標。goalid.isComplete == true。這里的目標 ID 是一個變量,未知。 使用 express 獲取 nodejs 的 [goalid, points].Mongodb 查詢等詳細信息。
這適用於 mongo shell 但不適用於 express 並且我無法獲取所需的屬性(目標,點)
db.tablename.find({$where: function() {for(var key in this.goals) {if (this.goals[key].isComplete == true) return true; }return false; }});
下面是表格數據(單行)
{
"_id": ObjectId("60fe7d8d48406eb3c8f6c3e5"),
"entityId": "abc",
"goals": {
"60fe7a9c793a7a7bb141715f": {
"isComplete": true,
"criteriaIds": {
"60fe7a9c793a7a7bb1417160": {
"isComplete": true,
"value": 5,
"completionDate": 1627361639350
}
},
"pointsAwarded": 100,
"completionDate": 1627361639350
},
"60fe7aaa793a7a7bb1417169": {
"isComplete": true,
"criteriaIds": {
"60fe7aaa793a7a7bb141716a": {
"isComplete": true,
"value": 101,
"completionDate": 1627361527428
}
},
"pointsAwarded": 50,
"completionDate": 1627361527428
},
"60ff907855b1412e4f087b64": {
"isComplete": true,
"criteriaIds": {
"60ff907955b1412e4f087b65": {
"isComplete": true,
"value": 101,
"completionDate": 1627361527428
}
},
"pointsAwarded": 50,
"completionDate": 1627361527429
}
},
"points": 200
}
嘗試使用這個
db.collection.aggregate([
{
$project: {
_id: 0,
goals: {
$objectToArray: "$goals"
}
}
},
{
$unwind: "$goals"
},
{
$match: {
"goals.v.isComplete": true
}
},
{
$project: {
goalid: "$goals.k",
points: "$goals.v.pointsAwarded",
},
}
])
輸出將是
[
{
"goalid": "60ff907855b1412e4f087b64",
"points": 50
},
{
"goalid": "60fe7a9c793a7a7bb141715f",
"points": 100
},
{
"goalid": "60fe7aaa793a7a7bb1417169",
"points": 50
}
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.