Database Reference
In-Depth Information
@actions = @db['user.actions']
40.times do |n|
doc = {
:username => "kbanker",
:action_code => rand(4),
:time => Time.now.utc,
:n => n
}
@actions.insert(doc)
end
First, you create a 1 KB capped collection called users.actions using the DB#create_
collection method. 7 Next, you insert 20 sample log documents. Each document con-
tains a username, an action code (stored as an integer from 0 through 3), and a time-
stamp. You've included an incrementing integer, n , so that you can identify which
documents have aged out. Now let's query the collection from the shell:
> use garden
> db.user.actions.count();
10
Even though you've inserted 20 documents, only 10 documents exist in the collection.
If you query the collection, you'll see why:
db.user.actions.find();
{ "_id" : ObjectId("4c55f6e0238d3b201000000b"), "username" : "kbanker",
"action_code" : 0, "n" : 10, "time" : "Sun Aug 01 2010 18:36:16" }
{ "_id" : ObjectId("4c55f6e0238d3b201000000c"), "username" : "kbanker",
"action_code" : 4, "n" : 11, "time" : "Sun Aug 01 2010 18:36:16" }
{ "_id" : ObjectId("4c55f6e0238d3b201000000d"), "username" : "kbanker",
"action_code" : 2, "n" : 12, "time" : "Sun Aug 01 2010 18:36:16" }
...
The documents are returned in order of insertion. If you look at the n values, it's clear
that the oldest document in the collection is the tenth document inserted, which
means that documents 0 through 9 have already aged out. Since this capped collec-
tion has a maximum size of 1024 bytes, and contains just 10 documents, you can con-
clude that each document is roughly 100 bytes in length. You'll see how to confirm
this assumption in the next subsection.
Before doing so, I should point out a couple more differences between capped
and standard collections. First, the index on _id isn't created by default for a capped
collection. This is a performance optimization; without an index, inserts take less
time. If you do want an index on _id , you can build the index manually. With no
indexes defined, it's best to think of a capped collection as a data structure that you
process sequentially in lieu of querying randomly. For this purpose, MongoDB pro-
vides a special sort operator for returning a collection's documents in natural
7
The equivalent creation command from the shell would be db.createCollection("users.actions",
{capped: true, size: 1024}) .
Search WWH ::




Custom Search