master
Raw Download raw file
 1// This script demonstrates some basic DB usage, in a self-contained manner.
 2// This is somewhat advanced, and you probably want to figure out basic scripts first.
 3// Or, you can just dive into the deep end.
 4//
 5// *** SEE ALSO *** the MongoDB documentation for 'find' and 'update'
 6function(context, args) {
 7	// set up a place to store all the intermediate steps, before we display them to ourselves at the end
 8	var results = {};
 9	
10	// if we have nothing in our DB, this will be kind of boring. So, let's add some entries.
11	#db.i({
12		_DEMO_DELETEME_: true,
13		demo_context: context
14	});
15	#db.i({
16		_DEMO_DELETEME_: true,
17		demo_args: args
18	});
19
20	
21	// let's first grab ONE entry (maybe an existing one, if any) where 'demo_context' exists
22	results['context'] = #db.f({demo_context: {$exists: true}}).first();
23	// and, all entries where _DEMO_DELETEME_ is set to true
24	results['all'] = #db.f({_DEMO_DELETEME_: true}).array();
25
26	// run an update on all relevant entries in our DB. $inc is one of the update functions that MongoDB provides; you might also want $set, or others
27	#db.u({_DEMO_DELETEME_: true}, {$inc: {update_count: 1}});
28	results['after_all_update'] = #db.f({_DEMO_DELETEME_: true}).array();
29
30	// now we'll update *only one* of the entries, and see what happens
31	#db.u1({_DEMO_DELETEME_: true}, {$inc: {update_count: 1}});
32	results['after_single_update'] = #db.f({_DEMO_DELETEME_: true}).array();
33	
34	// clean up after ourselves. WARNING: if you have any *other* entries matching this filter, they'll be wiped away, too.
35	#db.r({_DEMO_DELETEME_: true});
36
37	// and now we display the results
38	return results;
39}