This document discusses NoSQL databases and provides an example of using MongoDB to calculate a total sum from documents. Key points:
- MongoDB is a document-oriented NoSQL database where data is stored in JSON-like documents within collections. It uses map-reduce functions to perform aggregations.
- The example shows saving ticket documents with an ID and checkout amount to the tickets collection.
- A map-reduce operation is run to emit the checkout amount from each document. These are summed by the reduce function to calculate a total of 430 across all documents.
26. Sum(checkout)
# START SERVER
$ ~/opt/mongodb-1.3.0/bin/mongod
--dbpath=./db/mongodb.01/
--logpath=./log/mongodb.01
--port 30001
# START SHELL
$ ~/opt/mongodb-1.3.0/bin/mongo localhost:30001
connecting to: localhost:30001/test
type "help" for help
> show dbs
admin
local
28. Sum(checkout)
> var map = function() {
... emit(null, this.checkout)
... }
> var reduce = function(key, values) {
... var sum = 0
... for (var index in values) sum += values[index]
... return sum
... }
52. Sum(Checkout) by day
Calculate Checkout
> var map = function() {
... var checkout = 0
... for (var name in this.products) {
...... var product = this.products[name]
...... checkout += product.quantity * product.price
...... }
... emit(this.day, checkout)
}
> var reduce = function(key, values) {
... var sum = 0
... for (var index in values) sum += values[index]
... return sum
}
55. Sum(Checkout) by day
Data Normalization
> var map = function() {
... var checkout = 0
... for (var name in this.products) {
...... var quantity = this.products[name]
...... var price = db.product.findOne({ "_id": name }).price
...... checkout += quantity * price
...... }
... emit(this.day, checkout)
}
> var reduce = function(key, values) {
... var sum = 0
... for (var index in values) sum += values[index]
... return sum
}
83. Push Received
Messages from Server
Check for Messages _changes?
received by <account.id> filter=message/received&
after <timestamp> by=<account.id>&
after=<timestamp>
Send Message Save Document
to <account.id> to: <account.id>
84. Push Received
Messages from Server
_changes?filter=message/received&by=<account.id>&after=<timestamp>
function(document, request) {
var receivedByMe =
document.to === request.query.by
var receivedAfterLastTime =
document.receivedAt >= request.query.after
return receivedByMe && receivedAfterLastTime
}