Skip to content

2C. Loading and Querying Documents

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

CBMongoDB implements a chainable query syntax that those familiar to SQL querys will find convenient. It also simplifies the process dynamically generating search queries. Using our person entity, we created earlier, we can reset our entity and re-find it. The where() method accepts either where('name','value') arguments (which is equivalent to name=value) or where('name','operator','value'), which uses standard values like >, <, !=, etc. 1:

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

Let's change our person's phone number:

person.setPhone_Home('616-555-8789');

The we can save the record, with our update() method:

person.update();

We can use our dot notation to find that record again - note the use of reset() to ensure our query criteria is empty

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.getDocument());

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 don't actually need to use reset() at this point, since saving an entity automatically evicts any criteria, but it's a good practice when starting a new query)

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 and, if you're going be looping through a large number of documents, is the way to go. Because of the way the cursor operates, 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!');
}

Read the API documentation for details on the individual functions and arguments.


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