aggregation framework - Display all data in a row using mongodb -


i have collection mycollection,

id    datetime              myid   cost   flag  1  '2016-07-01t00:00:00'    2048      1    'o' 2  '2016-07-02t00:00:00'    2049      2    'o' 

if write sql query it

"select datetime, myid,flag, min(cost) mycollection group datetime, myid" 

it display fields in data e.g

  datetime, myid,flag, min(cost) 

but in mongo aggregation framework can group

db.mycollection.aggregate([     {         $group: {             _id: {                 datetime: '$datetime',                 myid: '$myid'             },             mincost: { $min: '$cost' }         }     } ]) 

which return me

datetime, myid, min(cost)  

but need "flag" field in single query. tried out $push works array.

in sql server, query

select datetime, myid,flag, min(cost) mycollection group datetime, myid 

is invalid in select list because column flag not contained in either aggregate function or group clause.

in mongodb, able include field flag in aggregate query, must apply accumulator operator on field , in case may either use $first or $last accumulator operators return field value within aggregation.

db.mycollection.aggregate([     {         "$group": {             "_id": {                 "datetime": '$datetime',                 "myid": '$myid'             },             "mincost": { "$min": '$cost' },             "flag": { "$first": '$flag' }         }     } ]) 

in above, $first accumulator operator applied on flag field return flag value first document each group. order defined if documents in defined order.


Comments

Popular posts from this blog

Load Balancing in Bluemix using custom domain and DNS SRV records -

oracle - pls-00402 alias required in select list of cursor to avoid duplicate column names -

python - Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>] error -