Monday, 15 September 2014

mongodb - Can't get aggregate to return results using an array element -



mongodb - Can't get aggregate to return results using an array element -

i have documents like:

{ "_id" : ... "args" : { "pos" : [ <x>, <y> ], ... } }

i trying min , max of <x> , <y> values using next aggregate pipeline. runs no values.

db.main.aggregate([ { '$match': { "args.pos": { '$exists': true} } }, { '$project': { 'x': "$args.pos.0", 'y': "$args.pos.1" } }, { '$group': { '_id': 'pos', 'xmin': { '$min': '$x' }, 'xmax': { '$max': '$x' }, 'ymin': { '$min': '$y' }, 'ymax': { '$max': '$y' }, 'hits': { '$sum': 1 } } }, { '$project': { 'hits': '$hits', 'xmin': '$xmin', 'xmax': '$xmax', 'ymin': '$ymin', 'ymax': '$ymax', '_id': 0 } } ])

and next output:

{ "result" : [ { "xmin" : [ ], "xmax" : [ ], "ymin" : [ ], "ymax" : [ ], "hits" : 281 } ], "ok" : 1 }

i have tried various different ways acces <x> , <y> values, i'm new @ , i'm missing something. help appreciated.

i think issue can't reach array. have tried next simpler query not success either:

db.main.findone({'function':'map'},{"arguments.pos":1}) { "_id" : objectid("5110407a2c8bea0f0d0000ce"), "arguments" : { "pos" : [ -87.90774999999735, 42.11036897863933 ] } } db.main.findone({'function':'map'},{"arguments.pos.0":1}) { "_id" : objectid("5110407a2c8bea0f0d0000ce"), "arguments" : { "pos" : [ ] } } db.main.findone({'function':'map'},{"arguments.pos[0]":1}) { "_id" : objectid("5110407a2c8bea0f0d0000ce"), "arguments" : { } }

i'm running mongo shell mongodb 2.2 if matters.

you can't utilize pos.0 syntax in projection. in find can utilize $slice operator instead, that's not yet allowed in $project.

however, can way; using $unwind , $group extract x , y values:

class="lang-js prettyprint-override">db.main.aggregate([ {$match: {'args.pos': {$exists: true}}}, {$unwind: '$args.pos'}, {$group: { _id: '$_id', x: {$first: '$args.pos'}, y: {$last: '$args.pos'} }}, {$group: { _id: null, xmin: {$min: '$x'}, xmax: {$max: '$x'}, ymin: {$min: '$y'}, ymax: {$max: '$y'}, hits: {$sum: 1} }}, {$project: {_id: 0, xmin: 1, xmax: 1, ymin: 1, ymax: 1, hits: 1}} ])

mongodb aggregate-functions

No comments:

Post a Comment