从Mongodb查询响应中检索值

时间:2017-12-02 11:31:19

标签: javascript node.js mongodb

我有一个mongodb聚合框架查询,如下所示。我无法解析以下查询的输出

 myModel.aggregate(
    [
        {
            "$match": { "$and": [{ "serviceActiveFlag": "Y" }, { "hospitalName": hospitalName }] }
        },
        //decompile array
        { $unwind: "$Treatment" },
        {
            $group: {
                _id: "$Treatment.departmentName", "procedureList": {
                    $push: { "procedureName": "$Treatment.name", "cost": "$Treatment.costLowerBound" }
                }
            }
        },
        {
            $project: {
                "_id": 0,
                "department": '$_id',
                "procedureList": 1
            }
        }

    ], function (err, result) {

    })

上述查询的输出如下所示

{
    "data": [
        {
            "procedureList": [
                {
                    "procedureName": "Root Canal",
                    "cost": 10200
                }
            ],
            "department": "Dental"
        },        
        {
            "procedureList": [
                {
                    "procedureName": "Bone Grafting",
                    "cost": 20000
                }
            ],
            "department": "Ortho"
        }
    ]
}

如何检索与密钥data对应的值?

我试过了result.data [0],但是我得到了未定义的错误

预期输出见下文

预期输出

[
        {
            "procedureList": [
                {
                    "procedureName": "Root Canal",
                    "cost": 10200
                }
            ],
            "department": "Dental"
        },        
        {
            "procedureList": [
                {
                    "procedureName": "Bone Grafting",
                    "cost": 20000
                }
            ],
            "department": "Ortho"
        }
    ]

2 个答案:

答案 0 :(得分:0)

我认为你忘了解析json数据,这就是为什么它无法索引,请使用下面的代码来解析json,然后尝试访问数组。如果您遇到任何问题,请提及。

result = JSON.parse(result)
result.data[0]

答案 1 :(得分:0)

结果是一个对象,

let data = result.data