combine multiple match() results in mongodb aggregation framework -
i got following query:
db.getcollection('messages').aggregate( { $match : { "header.messagetype" : { $in: ["04"] }, } }, { $project: { _id: '$_id', header: '$header', content: '$content', q0: { $arrayelemat: [ "$content.changes", 0 ] }, q1: { $arrayelemat: [ "$content.changes", 1 ] }, q2: { $arrayelemat: [ "$content.changes", 2 ] }, q3: { $arrayelemat: [ "$content.changes", 3 ] }, q4: { $arrayelemat: [ "$content.changes", 4 ] }, q5: { $arrayelemat: [ "$content.changes", 5 ] }, } }, { $match : { "q0":"1" } }, { $sort : { "sequenceid" : -1, } }, { $limit : 1 } );
which gives me following results:
/* 1 */ { "_id" : objectid("57288ecb53f65928c4ba4995"), "header" : { "messagetype" : "04", ... }, "content" : { ... }, "q0" : "1", "q1" : "0", "q2" : "1", "q3" : "0", "q4" : "0", "q5" : "0"
the query gives me recent document (according sequenceid) 'q0' equals 1 (other qx fields might 0 or 1). want same q1,q2,...,q5. in other words, want result containing 6 records each of representing recent document 'qn' (n=0..5) record '0'.
is possible repeat following part 6 times (for different qx values in $match section) , combine them?
{ $match : { "q0":"1" } }, { $sort : { "sequenceid" : -1, } }, { $limit : 1 }
or there better solution this?
--- edit (some sample [and simplified] data added):
/* 1 */ { "_id" : objectid("57288fa553f65928c4bf4b2b"), "header" : { "messagetype" : "04" }, "content" : { "changes" : [ "0", "1", "1", "1", "1", "0" ] }, "sequenceid" : numberlong(369851), "messagedate" : 13950214 } /* 2 */ { "_id" : objectid("57288fa453f65928c4bf4863"), "header" : { "messagetype" : "04" }, "content" : { "changes" : [ "0", "0", "1", "0", "0", "0" ] }, "sequenceid" : numberlong(369139), "messagedate" : 13950214 } /* 3 */ { "_id" : objectid("57288fa353f65928c4bf43c2"), "header" : { "messagetype" : "04" }, "content" : { "changes" : [ "0", "1", "0", "0", "0", "0" ] }, "sequenceid" : numberlong(367953), "messagedate" : 13950214 }
each document indicates 1 or more (up 6) modifications. modifications seen in q0..q5 fields. need output recent changes each qx field. order of documents can determined "sequenceid" field. in other words if (logically an) or q0..q5 of documents in result, should ["1","1","1","1","1","1"].
after $match executed - documents aren't selected removed process pipe.
what propose replace
{ $match : { "q0":"1" } },
with
{ $group:{ _id:{include fields here}, q0:{$push:"$q0"}, ..............., q5:{$push:"$q5"} }, }
after can operate on array having full result set.
so can use $filter
{ $filter: { input: "q0", as: q0filtered, cond: {$eq:1} } }
will work you?
any comments welcome!
Comments
Post a Comment