javascript - What's wrong with this mongoskin aggregation command? -
i have mongodb/mongoskin aggregation request follows:
db.collection(customertable + '_earnedinfluencers').aggregate([ { $group: { _id: '$user', name: '', // filled separately username: '', // filled separately picture: '', // filled separately city: '', // filled separately kids: { $sum: '$kids' }, revenue: { $sum: '$dayincome' }, kidsrevratio: { $divide: [ { $sum: '$kids' }, { $sum: '$dayincome' } ] } }, $match: { richness: { $gte: variable1 }, kids: { $lt: variable2 }, hobbies: { $in: ['hobby1', 'hobby2', 'hobby3', 'hobby4'] }, event: { $in: schoolfestival }, event: { $ne: 0 } }, $project: { _id: 0, user: '$_id', name: 1, username: 1, picture: 1, city: 1, kids: 1, revenue: 1, kidsrevratio: 1 } } ], function(err, result) { // err , result }); the above code gives following error:
error: {"name":"mongoerror","errmsg":"exception: pipeline stage specification object must contain 1 field.","code":16435,"ok":0} i'm new mongo , db in general, , can't tell did wrong.
your pipeline arguments unbalanced, each stage separate document need wrap each one. there number of other problems
db.collection(customertable + '_earnedinfluencers').aggregate([ { $match: { richness: { $gte: variable1 }, kids: { $lt: variable2 }, hobbies: { $in: ['hobby1', 'hobby2', 'hobby3', 'hobby4'] }, event: { $in: schoolfestival }, }}, { $group: { _id: '$user', name: { '$first': '$name' }, username: { '$first': '$username' }, picture: { '$first': '$picture' }, city: { '$first': '$city' } kids: { '$sum': '$kids' }, revenue: { '$sum': '$dayincome' }, kidssum: { '$sum': '$kids' }, }}, { $project: { _id: 0, user: '$_id', name: 1, username: 1, picture: 1, city: 1, revenue: 1, kidssum: 1, kidsrevratio: { $divide: [ '$kidssum', '$revenue' ] } }} ], function(err, result) { // err , result }); you had whole pipeline one document in fact requires array of documents shown.
but want $match first in order filter results. if want additional matching after group add in additional match pipeline afterwards.
the $group operation requires fields outside of _id grouping key need have "grouping operator" cannot fields own unless part of _id group on. typically want operator such $first or otherwise omit them completely.
top level grouping operators only, operations $divide not grouping operator. in order to sort of thing when working 1 or more $sum results move later $project using fields calculated values.
also operations project , group, "removes" fields pipeline , preserves include. cannot specify field not there. 1 reason why $match comes first can use index, , ever @ start of pipeline can done.
but each stage fields present mentioned. further optimization "optimizer" start not include fields present in document not mentioned. referenced in first match , group stages combined included rest of pipline stages, , possibly filtered down again.
Comments
Post a Comment