tuple/array in aggregation with $addToSet

963 views
Skip to first unread message

Christian Schulz

unread,
Jun 18, 2013, 11:51:54 AM6/18/13
to mongod...@googlegroups.com
Hi,

is there a simple way to overcome this problem?

Thanks in advance
Christian


col.aggregate([
    { '$group' : 
    {'_id' : {'anyid':"$anyid"},
    'loc' : {'$addToSet' : ('$lat','$lon') }}}])    

failed: exception: aggregating group operators are unary ($addToSet)

Gary R

unread,
Jun 18, 2013, 3:45:59 PM6/18/13
to mongod...@googlegroups.com
I believe that $addToSet, in aggregation framework, tries to push one object to an array.  It's complaining because ('$lat','$lon') appears to be two objects not a single tuple (if that's what you'd intended).  If you're trying to $addToSet one value after another, $addToSet now has an operator "each" which accepts an array of values.

{ $addToSet: { <array name> : { $each: [ value1, value2, etc ]  } } }

Gary R.

Asya Kamsky

unread,
Jun 25, 2013, 3:20:04 AM6/25/13
to mongod...@googlegroups.com
There is no $each operator in aggregation framework.
However all OP needs to do is change the document from {"$lat","$lon"} to { lon:"$lon", lat:"$lat"}  as the former is not legal JSON and the latter is.

Notice I also reverse the order of longitude and latitude as lon, lat is the expected order of coordinates in MongoDB.

Asya

Gary R

unread,
Jun 25, 2013, 11:24:21 AM6/25/13
to mongod...@googlegroups.com
Thanks for the correction, Asya.

So in aggregation, without "each," there is no way to push/addToSet just the values for TWO fields except within a document as you described?

If you have
{ _id:1, name:1, a:2, b:3 }
( _id:2, name:1, a:4, b:5 }

Is there no way to $group by $name and push BOTH $a and $b values into an array?

{ name:1, anArray[2,3,4,5] }

Gary R.

Asya Kamsky

unread,
Jun 27, 2013, 1:32:15 AM6/27/13
to mongod...@googlegroups.com
That's correct -there is no way to do this in aggregation framework right now.

Denis Pshenov

unread,
Feb 3, 2014, 6:32:46 AM2/3/14
to mongod...@googlegroups.com
That's unfortunate. Also needed this feature.
Reply all
Reply to author
Forward
0 new messages