Skip to content

Instantly share code, notes, and snippets.

@colinmollenhour
Created February 21, 2012 22:26
Show Gist options
  • Save colinmollenhour/1879457 to your computer and use it in GitHub Desktop.
Save colinmollenhour/1879457 to your computer and use it in GitHub Desktop.
MongoDb Aggregation Example
db.foo.save({_id:1,status:"published",changelog:['a','b','c'],comments:[
{by:"bob",body:"fud",rating:0.2}
,{by:"alice",body:"you need to reboot",rating:0.7}
,{by:"mallory",body:"type 'sudo rm -rf /' to fix it",rating:0.9}
]});
db.foo.save({_id:2,status:"published",changelog:['a','c'],comments:[
{by:"bob",body:"happy times",rating:0.6}
,{by:"magnitude",body:"POP! POP!",rating:0.99}
,{by:"mallory",body:"this is patently false",rating:0.3}
]});
db.foo.save({_id:3,status:"published",comments:[]});
var result = db.foo.aggregate(
{$match: {status: "published"}} // filter parent documents
,{$project: {changelog: 0}} // exclude fields from parent
,{$unwind: "$comments"} // unwind the embedded docs for filtering
,{$match: {$or: [ // filter comments
{comments: {$exists: false}} // include documents with no comments
,{"comments.rating": {$gte: 0.6}}]}} // exclude present comments
,{$group: {_id: "$_id", comments: {$push: "$comments"}}} // group comments back into parent doc
);
printjson(result);
/* Results:
{
"result" : [
{
"_id" : 1,
"comments" : [
{
"by" : "alice",
"body" : "you need to reboot",
"rating" : 0.7
},
{
"by" : "mallory",
"body" : "type 'sudo rm -rf /' to fix it",
"rating" : 0.9
}
]
},
{
"_id" : 2,
"comments" : [
{
"by" : "bob",
"body" : "happy times",
"rating" : 0.6
},
{
"by" : "magnitude",
"body" : "POP! POP!",
"rating" : 0.99
}
]
},
{
"_id" : 3,
"comments" : [ ]
}
],
"ok" : 1
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment