node.js - Returning a subset of array items in MongoDB -
can offer advice on how return subset of array items? example, let's suppose have collection of documents (similar example below) contains simple _id key , key contains array of objects.
i find _id's , matching objects match simple criteria:
// campaigns { "_id" : "fred's c25k", "campaigndata" : [ { "date" : "2015-06-17", "source" : "nike" }, { "date" : "2015-06-17", "source" : "reebok", }, { "date" : "2015-06-12", "source" : "nike" }, { "date" : "2015-06-14", "source" : "adidas" }, ] }, { "_id" : "mike's marathon", "campaigndata" : [ { "date" : "2015-06-17", "source" : "nike" } ] }, { "_id" : "jacob's jamboree", "campaigndata" : [ { "date" : "2015-06-17", "source" : "keen" } ] } i result contain _id , matching objects for, say, date value of "2015-06-17"
// goal => generate result set looks like: { "_id" : "fred's c25k", "campaigndata" : [ { "date" : "2015-06-17", "source" : "nike" }, { "date" : "2015-06-17", "source" : "reebok", } ] }, { "_id" : "mike's marathon", "campaigndata" : [ { "date" : "2015-06-17", "source" : "nike" } ] }, { "_id" : "jacob's jamboree", "campaigndata" : [ { "date" : "2015-06-17", "source" : "keen" } ] }
use aggregation framework achieve desired result. following pipeline consists of $match operator stage first step filter documents should pass through pipeline. next stage $unwind operator deconstructs campaigndata array field input documents output document each element. each output document replaces array element value. need $match step subdocuments match given date criteria. matched documents used in next $group pipeline step preserve original array using $push group accumulator operator:
db.collection.aggregate([ { "$match": { "campaigndata.date" : "2015-06-17" } }, { "$unwind": "$campaigndata" }, { "$match": { "campaigndata.date" : "2015-06-17" } }, { "$group": { "_id": "$_id", "campaigndata": { "$push": "$campaigndata" } } } ]) result:
/* 0 */ { "result" : [ { "_id" : "mike's marathon", "campaigndata" : [ { "date" : "2015-06-17", "source" : "nike" } ] }, { "_id" : "jacob's jamboree", "campaigndata" : [ { "date" : "2015-06-17", "source" : "keen" } ] }, { "_id" : "fred's c25k", "campaigndata" : [ { "date" : "2015-06-17", "source" : "nike" }, { "date" : "2015-06-17", "source" : "reebok" } ] } ], "ok" : 1 }
Comments
Post a Comment