Hari
Hari

Reputation: 394

Querying based on available partial data of nested document (in morphia, mongoDB)

Document structure (just for illustration)

Employee

{
name : "..",
age : ..,
addresses   [
  {
     "street":"...",
     "country":{
        name:"..",
        continent:"..",
        Galaxy:".."
     }
  }
],
company:".."
}

Query -

I have just Addresses -> street (type String) and Addresses -> country -> name (type String). And i want to get all employees that match this criteria.

Address a1 = new Address();
a1.setStreet("bla bla");
Country c = new Country();
c.setName("sth");
a1.setCountry(c);

Query<Employee> q = ds.createQuery(Employee.class).field("addresses").hasThisElement(a1)

DOESN'T fetch results (when actually there is a real match). Looks like its because of partial "Country" document match. If i populate all fields of Country its getting results as expected.

Question #1 : Any workaround for above?

Question #2 : Address is an array and i can get multiple (address#street, country#name) pairs and again i want the list of employees that match given pairs. Something like:

Query<Employee> q =  ds.createQuery(Employee.class).field("addresses").hasThisElement(a1).field("addresses").hasThisElement(a2).field(..) // and so on

Note: i can breakdown address match something like this

Address a = new Address();
a.setStreet("bla bla");
q.createQuery(Employee.class).field("addresses").hasThisElement(a).field("addresses.country.name").equal("hoo");

BUT this will match Employee where street="bla bla" and country.name!="hoo" in address#1 and street!="bla bla" and country.name="hoo" in address #2. You get the point. I don't want such Employees to be returned.

Please let me know if this is possible. Thanks much.

Upvotes: 1

Views: 1884

Answers (1)

spf13
spf13

Reputation: 561

It's possible. MongoDB has a special operator for situations like this called elemMatch. Morphia has support for it.

You are correct that the second approach is the right way (The first approach is trying to match the entire country, not the subkey). The only thing is you want to constrain it to a single element with both street and country.name matching. Not a document with a matching street and a matching country.name.

This doc page and this thread have some more information.

http://code.google.com/p/morphia/wiki/Query

http://groups.google.com/group/morphia/tree/browse_frm/month/2011-02/5bd3f654526fa30b?rnum=41&lnk=ol

Unfortunately I don't know morphia well, but hopefully that will give you enough information to solve it.

Upvotes: 1

Related Questions