【问题标题】:How to fetch data from nested json in mongodb when key is not known(variable)当密钥未知(变量)时如何从 mongodb 中的嵌套 json 中获取数据
【发布时间】:2021-10-03 21:36:13
【问题描述】:

我如何获取已实现目标的用户列表,即goals.goalid.isComplete == true。这里的目标ID 是一个变量并且未知。 获取详细信息,例如 [goalid, points].Mongodb 使用 express 查询 nodejs。

这在 mongo shell 中有效,但不适用于 express,我无法获取所需的属性(goalid、points)

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
    }

【问题讨论】:

  • 您可以尝试使用$objectToArray 运算符进行聚合查询。

标签: node.js json mongodb express


【解决方案1】:

试试这个

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
  }
]

试试mongoplayground

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    • 2013-05-23
    • 2022-07-20
    • 1970-01-01
    相关资源
    最近更新 更多