[confluence] MongoDB > Use Case - Session Objects

4 views
Skip to first unread message

nor...@mongodb.onconfluence.com

unread,
Jan 25, 2013, 10:10:00 AM1/25/13
to mongodb...@googlegroups.com

Use Case - Session Objects

Page edited by Sam Kleinman


Changes (3)

MongoDB is a good tool for storing HTTP session objects.
{redirect:http://docs.mongodb.org/manual/tutorial/expire-data/}
One implementation model is to have a sessions collection, and store the session object's \_id value in a browser cookie.


With its update-in-place design and general optimization to make updates fast, the database is efficient at receiving an update to the session object on every single app server page view.

h3. Aging Out Old Sessions


The best way to age out old sessions is to use the auto-LRU facility of [capped collections|DOCS:Capped Collections].  The one complication is that objects in capped collections may not grow beyond their initial allocation size.  To handle this, we can "pre-pad" the objects to some maximum size on initial addition, and then on further updates we are fine if we do not go above the limit.  The following mongo shell javascript example demonstrates padding.

(Note: a clean padding mechanism should be added to the db so the steps below are not necessary.)

{code}
> db.createCollection('sessions', { capped: true, size : 1000000 } )
{"ok" : 1}
> p = "";
> for( x = 0; x < 100; x++ ) p += 'x';
> s1 = { info: 'example', _padding : p };
{"info" : "example" , "_padding" : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}
> db.sessions.save(s1)
> s1
{"info" : "example" , "_padding" : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" , "_id" : ObjectId( "4aafb74a5761d147677233b0") }

> // when updating later
> s1 = db.sessions.find( { _id : ObjectId( "4aafb74a5761d147677233b0") } )
{"_id" : ObjectId( "4aafb74a5761d147677233b0") , "info" : "example" , "_padding" : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}
> delete s._padding;
true
> s.x = 3; // add a new field
3
> db.sessions.save(s);
> s
{"_id" : ObjectId( "4aafb5a25761d147677233af") , "info" : "example" , "x" : 3}
{code}

Full Content

Redirection Notice
This page should redirect to http://docs.mongodb.org/manual/tutorial/expire-data/.

nor...@mongodb.onconfluence.com

unread,
Jan 25, 2013, 10:10:00 AM1/25/13
to mongodb...@googlegroups.com
Reply all
Reply to author
Forward
0 new messages