use mark db.books.drop() db.step1.drop() db.books.insertMany( [ {name : "book1", locations : [ { "store1" : 1}, { "store2" : 2}, { "store3" : 3} ], type : 'fiction' } , {name : "book2", locations : [ { "store1" : 4}, { "store3" : 5}, { "store4" : 6} ], type : 'fiction' } , {name : "book2", locations : [ { "store6" : 13}, { "store9" : 14}, { "store13" : 15} ], type : 'fiction' } , {name : "book3", locations : [ { "store2" : 7}, { "store4" : 8}, { "store5" : 9} ], type : 'nonfiction' } {name : "book3", locations : [ { "store5" : 10}, { "store6 : 11}, { "store5" : 12} ], type : 'nonfiction' } ] ); print ("First aggregation just filters 'book1' out of documents.") db.books.aggregate([ {$match : { 'name' : 'book1'}}, { $out : "step1" } ]) db.step1.find().forEach(printjson); print ("Second aggregation counts total for each book entry.") db.books.aggregate([ { { _id: "$name", totalQuantity: { $sum: "$quantity" } } } { $out : "step1" } ]) db.step1.find().forEach(printjson); print (' many more examples will be added')