将MongoDB查询结果转换为JSONArray

时间:2015-07-23 16:58:01

标签: javascript arrays json node.js mongoose

我通过mongoose进行MongoDB查询,结果是:

[
  {
    "tablename": "name1"
  },
  {
    "tablename": "name2"
  }
]

但我需要它作为JSONArray:

{
  "tablename": [
    "name1",
    "name2"
  ]
}

有一种简单的转换方法吗?

3 个答案:

答案 0 :(得分:1)

aggregation framework 可以为您创建所需的结果。考虑 $group $push 累加器运算符,如下所示:

db.collection.aggregate([
    {
        "$group": {
            "_id": null,
            "tablename": {
                "$push": "$tablename"
            }           
        }
    },
    {
        "$project": {
            "_id": 0, "tablename": 1
        }
    }    
])

示例输出:

/* 0 */
{
    "result" : [ 
        {
            "tablename" : [ 
                "name1", 
                "name2"
            ]
        }
    ],
    "ok" : 1
}

您可以使用 aggregate() 方法在mongoose中实现此功能,例如:

var pipeline = [
        {
            "$group": {
                "_id": null,
                "tablename": {
                    "$push": "$tablename"
                }           
            }
        },
        {
            "$project": {
                "_id": 0, "tablename": 1
            }
        }    
    ]

Model.aggregate(pipeline).exec(function (err, res){
    console.log(res);
})

<强>更新

更改此查询以使用聚合框架:

app.post('/getkost', function(request, response){ 
    var kost = new RegExp(request.body.kost,'i'); 
    Move.find(
        { tablename: { $regex: kost } },
        { tablename: 1, _id: 0 }, 
        function(err, doc) { 
            response.json(doc); 
    }); 
});

到此:

app.post('/getkost', function(request, response){ 
    var kost = new RegExp(request.body.kost, 'i'); 
    var pipeline = [
        {
            "$match": {
                "tablename": { "$regex": kost }
            }
        },
        {
            "$group": {
                "_id": null,
                "tablename": {
                    "$push": "$tablename"
                }           
            }
        },
        {
            "$project": {
                "_id": 0, "tablename": 1
            }
        }
    ]
    Move.aggregate(pipeline, function(err, res) { 
        response.json(res); 
    }); 
});

答案 1 :(得分:0)

尝试...

service

答案 2 :(得分:0)

这应该适合你:

var json = [{
    "tablename": "name1"
}, {
    "tablename": "name2"
}]

var arr = {};
json.forEach(function(value, key) {
    var tableName = Object.keys(json[key]);
    arr[tableName] = arr[tableName] || [];
    arr[tableName].push(value[tableName]);
});

console.log(arr);

Fiddle

请注意Object.keys()实际上会返回一个数组 - 如果您的数组包含多个键(例如{"tablename": "name1", "othertablename": "name2"}