Query the map size in MongoDB -
suppose have map of variable size in mongodb. how can documents have map size, example >2?
{map:{k1:v1, k2:v2, k3,v3}} {map:{k1:v1, k2:v2}}
you'd need pre-calculate such map size if want queries on them later consider creating new field "keycount"
holds number of keys map subdocument. consider following demonstration:
populate test collection
db.test.insert([ { "_id" : 1, "map" : { "k1" : "v1", "k2" : "v2", "k3" : "v3" } }, { "_id" : 2, "map" : { "k1" : "v1", "k2" : "v2" } } ]);
as current design, need mechanism count of keys inside map document. possible through map-reduce. following mapreduce operation populate separate collection new field "keycount"
added:
var mr = db.runcommand({ "mapreduce": "test", "map" : function() { var obj = this; obj['keycount'] = object.keys(this.map).length; emit(this._id, obj); }, "reduce" : function(key, stuff) { return null; }, "out": "my_collection" + "_keys" })
to documents have map size, example > 2
, run query on resulting collection:
db[mr.result].find({ "value.keycount": { "$gt": 2 } });
map reduce output
/* 0 */ { "result" : "my_collection_keys", "timemillis" : 7, "counts" : { "input" : 2, "emit" : 2, "reduce" : 0, "output" : 2 }, "ok" : 1 }
query output
/* 0 */ { "_id" : 1, "value" : { "_id" : 1, "map" : { "k1" : "v1", "k2" : "v2", "k3" : "v3" }, "keycount" : 3 } }
Comments
Post a Comment