Skip to content

2C. Loading and Querying Documents

Jon Clausen edited this page Dec 21, 2015 · 3 revisions

Now let's reset our entity and re-find it. The where() method accepts either where('name','value') arguments or where('name','operator','value') 1:

person = person.reset().where('first_name','John').where('last_name','Doe').find();

Let's change our phone number:

person.set('phone.home','616-555-8789').update();

We can use our dot notation to find that record again

person = person.reset().where('phone.home','616-555-8789').find()

Now let's duplicate that document so we can play with multiple record sets

var newperson = structCopy(person.get_document());

structDelete(newperson,'_id');

newperson = this.reset().populate(newperson).set('first_name','Jane').set('last_name','Doe').create();

Now we can find our multiple records - which will return an array (Note: We probably don't need to use reset(), but it's a good practice to clear any active query criteria from previous queries)

var people = this.reset().findAll();	

for(var peep in people){
	writeOutput("#peep.first_name# #peep.last_name# is in the house!");
}

Here's where we diverge from RDBMS: MongoDB uses a "cursor" on multiple record sets. It is extremely fast (with some limitations) and, if you're going be looping through a large number of documents, is the way to go. Because of the way the cursor is designed, it doesn't actually start executing queries on the database until the first time a record is requested. If we use the "asCursor" argument in findAll(boolean asCursor=false,boolean asJSON=false), we recevie the cursor back:

var people = this.reset().findAll(true);  //or findAll(asCursor=true), if you're feeling verbose	

while(people.hasNext()){
	var peep=people.next();
	writeOutput('#peep.first_name# #peep.last_name# is in the house!');
}

Lastly, let's clean up our test documents. The delete() function allows a boolean argument of "truncate" which defaults to FALSE. If you set this argument to true, without a loaded record or existing criteria, it will delete all documents from the collection. In this case, we're just going to delete our records one at a time, using our cursor:

var people = this.reset().findAll(true);

while(people.hasNext()){
	var peep=people.next();
	//notice how we're using bracket notation for our _id value. This is necessary because calling peep._id on the cursor object will throw an error  
	this.get(peep['_id']).delete();
}
	

Optionally, you could delete all records matching a given criteria using a where() clause:

var noDoes = this.reset().where('last_name','Doe').delete();

That's basic CRUD functionality. Read the API documentation for details on the individual functions and arguments.


1 Valid operators currently include "=","!=","<",">",">=","<=","IN" and "Exists"

Clone this wiki locally