javascript - how to query nested JSON using mongodb -
i have json this:
"marks":{ "sem1" :{ "mark1":10, "total":100 }, "sem2":{ "mark2":20, "total":200 }, "sem3":{ "mark2":30, "total":300 } }
i need result
mark total sem 10 100 sem1 20 200 sem2 30 300 sem3
how can achieve above format using monogodb query.query
jaspersoft related means useful.
this not structure if not in control need mapreduce javascript processing:
db.collection.mapreduce( function () { var doc = this, marks = doc.marks; object.keys( marks ).foreach(function(key) { //emit( key, doc["marks"][key] ); var matched = object.keys( marks[key] ).filter(function(inner) { return inner.match(/^mark/); }); if ( matched.length > 0 ) { //emit( matched[0], 1 ); var mymatched = matched[0]; emit( marks[key][mymatched], { total: marks[key].total, sem: key } ); } }); }, function() {}, // null reducer not required { "out": { "inline": 1 } } );
not desired result, way mapreduce it. required because structure cannot queried or analysed traditional means.
to better need instead:
{ "marks": [ { "semester": "sem1", "mark": 10, "total": 100 }, { "semester": "sem2", "mark": 20, "total": 200 }, { "semester": "sem3", "mark": 30, "total": 300 } ] }
then query aggregation framework, better uses native code , not javascript notation traverse:
db.collection.aggregate([ { "$unwind": "$marks" }, { "$project": { "mark": "$marks.mark", "total": "$marks.total", "sem": "$marks.semester" }} ])
you can more, debatable on sample given want achieve.
Comments
Post a Comment