gpt4 book ai didi

javascript - 将 MongoDB 查询结果转换为 JSONArray

转载 作者:太空宇宙 更新时间:2023-11-04 00:52:47 25 4
gpt4 key购买 nike

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

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

但我需要它作为 JSONArray :

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

有没有简单的转换方法?

最佳答案

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);
});
});

关于javascript - 将 MongoDB 查询结果转换为 JSONArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31593670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com