Get the count of Fields in each document through query using MongoDB java driver -
is possible number of fields in document using query mongodb java driver
example:
document1 :{_id:1,"type1": 10 "type2":30,"abc":123,"def":345} document2 :{_id:2,"type2":30,"abc":123,"def":345} note: in second document "type1" key doesnt exist .
when project
is possible project "type1" , "type2" , number of fields existing in document.
with current code getting documents , individually searching if there key looking present in whole cursor: code snipped follows:
mongoclient mcl=new mongoclient(); mongodatabase mdb=mcl.getdatabase("test"); mongocollection mcol=mdb.getcollection("testcol"); finditerable<document> finditerable = mcol.find(); mongocursor<document> cursor = finditerable.iterator(); //here having 120 types checking if each type present.. while(cursor.hasnext()) { document doc=cursor.next(); int numberoftypes=0; for(int i=1;i<=120;i++) { if(doc.containskey("type"+i)) { numberoftypes++; } } system.out.println("*********************************************"); system.out.println("_id"+doc.get("_id")); system.out.println("number of types in document "+numberoftypes); system.out.println("*********************************************"); } } this code working if records less wont on load application ..suppose there 5000000 each document containing 120 types , application crashing there more garbage collection involved every iteration creating document.is there other approach through can achieve above stated functionality.
from java code read
project "type1" , "type2" , number of fields existing in document.
as
project type[1..120] fields , number of such fields in document with assumption, can map-reduce following:
db.testcol.mapreduce( function(){ value = {count:0}; (i = 1; <= 120; i++) { key = "type" + if (this.hasownproperty(key)) { value[key] = this[key]; value.count++ } } if (value.count > 0) { emit(this._id, value); } }, function(){ //nothing reduce }, { out:{inline:true} }); out:{inline:true} works small datasets, when result fits 16mb limit. larger responses need output collection, can query , iterate usual.
Comments
Post a Comment