Hello Fumiko,
I think the following examples may help, but please let me know if this is not what you are trying to accomplish.
A female in the US purchases an umbrella for $100. We insert a document:
> doc =
{ _id : 1,
product: "umbrella",
sale_amount : 100.00,
sale_count: 1,
gender : female,
country : USA,
}
> db.collection.insert(doc)
Another female in the US purchases an umbrella for $86, and we would like to update the document to adjust the sale amount and count:
> db.collection.update({product: "umbrella", gender: female, country: USA}, {$inc: {sale_amount: 86, sale_count: 1}})
> db.collection.find()
{ _id : 1,
product: "umbrella",
sale_amount : 186.00,
sale_count: 2,
gender : female,
country : USA,
}
Alternatively, you can insert a new document every time a purchase is made, and perform aggregation at a later point. The advantage of this procedure is that you maintain a record of every purchase (useful for tracking), but the disadvantage is that your data size will grow, and in addition, the aggregation command may be more expensive than a simple update with $inc. Here is an example of aggregation using the aggregation framework:
{ _id : 1,
product: "umbrella",
sale_amount : 100.00,
gender : "female",
country : "USA",
}
{ _id : 2,
product: "umbrella",
sale_amount : 86.00,
gender : "female",
country : "USA",
}
> db.collection.aggregate(
{$match: {product: "umbrella", gender: "female", country: "USA"}},
{$group:
{ _id: {product: "$product", gender: "$gender", country: "$country"},
count: {$sum: 1},
totalAmount: {$sum: "$sale_amount"}
}
})
{
"result" : [
{
"_id" : {
"product" : "umbrella",
"gender" : "female",
"country" : "USA"
},
"count" : 2,
"totalAmount" : 186
}
],
"ok" : 1
}
Map Reduce involves first emitting, and subsequently grouping, documents. The process is similar to the aggregation command above. The advantage of MR is that you can output the results to a new collection; however, since MR uses Javascript (and MongoDB currently uses a single-threaded Javascript engine), the performance may not be as good as the aggregation framework. Nevertheless, if you would like sample MR functions, please let me know.