If your query uses an aggregation operator, then the solution is a sample using $ out.
I created a Collection sample called "tester" that contains the following entries.
{ "_id" : ObjectId("4fb36bfd3d1c88bfa15103b1"), "name" : "bob", "value" : 5, "state" : "b"} { "_id" : ObjectId("4fb36c033d1c88bfa15103b2"), "name" : "bob", "value" : 3, "state" : "a"} { "_id" : ObjectId("4fb36c063d1c88bfa15103b3"), "name" : "bob", "value" : 7, "state" : "a"} { "_id" : ObjectId("4fb36c0c3d1c88bfa1a03b4"), "name" : "john", "value" : 2, "state" : "a"} { "_id" : ObjectId("4fb36c103d1c88bfa5103b5"), "name" : "john", "value" : 4, "state" : "b"} { "_id" : ObjectId("4fb36c143d1c88bfa15103b"), "name" : "john", "value" : 8, "state" : "b"} { "_id" : ObjectId("4fb36c163d1c88bfa15103a"), "name" : "john", "value" : 6, "state" : "a"}
Now, using the aggregate operator, I execute the group, and then save the result to a new collection using this magic "$ out" operator.
db.tester.aggregate([{$group:{ _id:{name:"$name",state:"$state"}, min:{$min:"$value"}, max:{$max:"$value"}, } }, {$out:"tester_max_min"} ])
What basically tries to execute the query is to group by name and state and find the minimum and maximum values ββfor each individual group, and then save the result in a new collection called "tester_max_min"
db.tester_max_min.find();
The newly formed collection will contain the following documents:
{ "_id" : { "name" : "john", "state" : "b" }, "min" : 4, "max" : 8 } { "_id" : { "name" : "john", "state" : "a" }, "min" : 2, "max" : 6 } { "_id" : { "name" : "bob", "state" : "a" }, "min" : 3, "max" : 7 } { "_id" : { "name" : "bob", "state" : "b" }, "min" : 5, "max" : 5 }
I still need to learn how useful it is to use $ out, but it works like a charm for any aggregator operator.