node.js - MongoDB to return assoc array of results -


my collection has object following form

{'id':2, 'name':'john', 'avatar':'img.png'}, {'id':3, 'name':'chriss', 'avatar':'img2.png'} 

after query mongo, want following results

{'2': {'id':2, 'name':'john', 'avatar':'img.png'}, '3':{'id':3, 'name':'chriss', 'avatar':'img2.png'}} 

is possible mongo or have iterate on results form ?

you try iterating on results using find() cursor's foreach() method follows :

var obj = {}; db.collection.find({}, {"_id": 0}).foreach(function(doc){     obj[doc.id.tostring()] = doc; }); printjson(obj); 

or using map() method:

var mapped = db.collection.find({}, {"_id": 0}).map(function(doc){     var obj = {};     obj[doc.id.tostring()] = doc;     return obj; }); printjson(mapped); 

output in both methods:

{         "2" : {                 "id" : 2,                 "name" : "john",                 "avatar" : "img.png"         },         "3" : {                 "id" : 3,                 "name" : "chriss",                 "avatar" : "img2.png"         } } 

Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -