javascript - Convert MongoDB query result into JSONArray -


i have mongodb query via mongoose , result is:

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

but need jsonarray :

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

is there easy way convert?

the aggregation framework can create desired result you. consider $group , $push accumulator operators follows:

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

sample output:

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

you can implement in mongoose using aggregate() method, example:

var pipeline = [         {             "$group": {                 "_id": null,                 "tablename": {                     "$push": "$tablename"                 }                        }         },         {             "$project": {                 "_id": 0, "tablename": 1             }         }         ]  model.aggregate(pipeline).exec(function (err, res){     console.log(res); }) 

update

change query use aggregation framework:

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

to this:

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

Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

Nuget pack csproj using nuspec -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -