My favorites | Sign in
Project Home Downloads Wiki Issues Source
Search
for

Query  
How to Query
Updated Nov 23, 2011 by scotthernandez

Introduction

The Query interface is pretty straight forward. It allows for certain filter criteria (based on fields), sorting, an offset, and limiting of the number of results.

The query implementation also implements the the QueryResults interface which allows access to the data from the query.

Filter

The generic .filter(criteria, value) syntax is supported. The criteria is a composite of the field name and the operator ("field >", or "field in"). All criteria are implicitly combined with a logical "and".

Datastore ds = ...
Query q = ds.createQuery(MyEntity.class).filter("foo >", 12);

Finding entities where foo is between 12 and 30 would look like this:

Datastore ds = ...
Query q = ds.createQuery(MyEntity.class).filter("foo >", 12).filter("foo <", 30);

Operators

The operators used in filter(...) match the MongoDB query operators very closely.

operatormongo op
= $eq
!=, <> $ne
>, <, >=,<= $gt, $lt, $gte, $lte
in $in
nin $nin
elem $elemMatch
exists $exists
all $all
size $size
... ...

Fluent Interface

Along with the .filter(...) method there are fluent query methods as well. These provide a more readable (like in the english language sense) form.

The fluent interface works by starting with field(name). Then any of the following methods can be added to form the filtering part of the criteria.

Query q = ds.createQuery(MyEntity.class).field("foo").equal(1);

q.field("bar").greaterThan(12);
q.field("bar").lessThan(40);

Methods

method operation comment
exists $exists
doesNotExist $exists
greaterThan, greaterThanOrEq, lessThan, lessThanOrEq $gt, $gte, $lt, $lte
equal, notEqual $eq, $ne
hasThisOne $eq
hasAllOf $all
hasAnyOf $in
hasNoneOf $nin
hasThisElement $elemMatch
sizeEq $size

Geo-spatial

All of the geo-spatial query methods break down into "near, and within". All of the near queries will produce results in order of distance, closest first. All of the methods below also accept a final parameter of spherical to indicate if they should use the new $sphere option.

method operation comment
near(x,y) $near
near(x,y,r) $near (w/maxDistance of r)
within(x,y,r) $within + $center
within(x1,y1,x2,y2) $within + $box

@Entity
static private class Place {
	@Id protected ObjectId id;
	protected String name = "";
	@Indexed(IndexDirection.GEO2D)
	protected double[] loc = null;
	
	public Place(String name, double[] loc) {
		this.name = name;
		this.loc = loc; }

	private Place() {}
}

Place place1 = new Place("place1", new double[] {1,1});
ds.save(place1);

Place found = ds.find(Place.class).field("loc").near(0, 0).get();

Or

Using the fluent query interface you can also do "or" queries like this:

Query<Person> q = ad.createQuery(Person.class);
q.or(
	q.criteria("firstName").equal("scott"),
	q.criteria("lastName").equal("scott")
); 

Note: In this example the method criteria is used. It you use field}} as one of the {{{or parameters then you will get a compiler error.

Fields

Field names can be used much like they can in native mongodb queries, with "dot" notation.

Query q = ds.createQuery(Person.class).field("addresses.city").equal("San Francisco");
//or with filter, or with this helper method
Query q = ds.find(Person.class, "addresses.city", "San Francisco");

Validation

Validation is done on the field names, and data types used. If a field name is not found on the java class specified in the query then an exception is thrown. If the field name is in "dot" notation then each part of the expression is checked against your java object graph (with the exception of a map, where the key name is skipped).

Problems in the data type (comparing the field type and parameter type) are logged as warnings since it is possible that the server can coerce the values, or that you meant to send something which didn't seem to make sense; The server uses the byte representation of the parameter so some values can match even if the data types are different (numbers for example).

Disabling Validation

Validation can be disabled by calling disableValidation() as the beginning of the query definition, or anywhere within you query.

Datastore ds = ...
Query q = ds.createQuery(MyEntity.class).disableValidation();

//or it can be disabled for just one filter

Query q = ds.createQuery(MyEntity.class).disableValidation().filter("someOldField", value).enableValidation().filter("realField", otherVal);

Sort

You can sort by a field, or multiple fields in ascending or descending order.

Datastore ds = ...
Query q = ds.createQuery(MyEntity.class).filter("foo >", 12).order("dateAdded");
... // desc order
Query q = ds.createQuery(MyEntity.class).filter("foo >", 12).order("-dateAdded");
... // asc dateAdded, desc foo
Query q = ds.createQuery(MyEntity.class).filter("foo >", 12).order("dateAdded, -foo");

Limit

You can also limit for the number of elements.

Datastore ds = ...
Query q = ds.createQuery(MyEntity.class).filter("foo >", 12).limit(100);

Offset (skip)

You can also ask the server to skip over a number of elements on the server by specifying an offset value for the query. This will less efficient than a range filter using some field, for pagination for example.

Datastore ds = ...
Query q = ds.createQuery(MyEntity.class).filter("foo >", 12).offset(1000);

Ignoring Fields

MongoDB also supports only returning certain fields. This is a little strange in application but it is an important way to trim parts off of embedded graphs. This will lead to partial entities and should be used sparingly, if at all.

Datastore ds = ...
MyEntity e = ds.createQuery(MyEntity.class).retrievedFields(true, "foo").get();

val = e.getFoo(); // only field returned

...

MyEntity e = ds.createQuery(MyEntity.class).retrievedFields(false, "foo").get();

val = e.getFoo(); // only field not returned

The field name argument (the last arg) can be a list of strings or a string array:

MyEntity e = ds.createQuery(MyEntity.class).retrievedFields(true, "foo", "bar").get();

val = e.getFoo(); // fields returned
vak = e.getBar(); // fields returned

Returning Data

To return your data just call one of the QueryResults methods. None of these methods affect the Query. They will leave the Query alone so you can continue to use it to retrieve new results by calling these methods again.

methoddoes
get() returns the first Entity -- using limit(1)
asList() return all items in a List -- could be costly with large result sets
fetch() explicit method to get Iterable instance
asKeyList() return all items in a List of their Key<T> -- This only retrieves the id field from the server.
fetchEmptyEntities() Just like a fetch() but only retrieves, and fills in the id field.

Datastore ds = ...
Query q = ds.createQuery(MyEntity.class).filter("foo >", 12);

//single entity
MyEntity e = q.get();

e = q.sort("foo").get();

//for
for (MyEntity e : q)
  print(e);

//list
List<MyEntity> entities = q.asList();
Comment by kratos00...@gmail.com, May 26, 2011

hi, how to force Query references with Eager?

:) sorry about my bad English

Comment by jm...@exoanalytic.com, Jun 13, 2011

Let's say I want to use the fluent interface to find which Persons have an Address is equal to addr:

Query<Person> = ds.createQuery(Person.class).field("address").equal(addr);

How is equality determined? Is Morphia essentially confirming that addr.id equals Person.address.id? This would imply that you can't query for equality against an object that has not been saved the db - is this correct? Thanks!

Comment by goudreau...@gmail.com, Jul 16, 2011

Does the generic filter accept patterns ?

Comment by sc...@10gen.com, Jul 16, 2011

jm..., It will compare all the fields. If you just want to match on a single field, then use that field (using dot-notation).

Comment by sc...@10gen.com, Jul 16, 2011

goudreau: do you mean like a regular expression?

It is best to ask questions on the group/list, please follow up there.

Comment by jianghai...@gmail.com, Jul 27, 2011

I do not see any support for limit(), is that the case?

Comment by project member scotthernandez, Jul 27, 2011

There is support for limit; I will add some docs.

Comment by caoxin1...@gmail.com, Oct 8, 2011

(condition_A1 && condition_A2 && condition_A3)

|| (condition_C1 && condition_C2 && condition_C3)
(condition_B1 && condition_B2 && condition_B3)

how to use query to do?

Comment by xer...@gmail.com, Nov 17, 2011

I've got the same problem. How to use query to do:

(condition_A1

|| condition_A3) && (condition_B1 || condition_B3) && (condition_C1 || condition_C3)
condition_A2
condition_B2
condition_C2

Thanks in advance

Comment by kubu...@gmail.com, Yesterday (22 hours ago)

hi I want to search in a map type field. For example:

p <contry,city> q.field(p).hasAnyOf("Istanbul");

how can I do that?

ps: it's not working of course.


Sign in to add a comment
Powered by Google Project Hosting