$elemMatch Query questions

1,275 views
Skip to first unread message

Brian KimJohnson

unread,
Feb 6, 2011, 12:45:59 AM2/6/11
to Morphia
Greetings all,



Using Morphia on a project and it has been great thus far so thanks
for all the work!


I am having trouble making this query in Morphia. Can some tell me
how to run a complex $elemMatch


db.BaseActivity.find(
{ "_id" : ObjectId("4d4a19cc93fb69115e88e82c") ,
"rs" : { "$elemMatch" :
{ "_id" : ObjectId("4d4a1d0fdda16911f16ac0ac") ,
"l" : { "$nin" : [ 127]}}
}
})

Notice that for this query I am specifying an array of embedded object
"rs". In order to select an object from the array I am searching for
an id and making sure that the array "l" does not contain 127.


Can this query be done using Morphia? I know how to generate it with
only the _id filter but how can I do both?


*Sample query for only one attribute:
Query updateQuery = ds.createQuery(parent.getClass()).filter("_id",
parent.getId());


Thanks!

Scott Hernandez

unread,
Feb 6, 2011, 2:04:31 AM2/6/11
to mor...@googlegroups.com

There is not an easy way to express that query with the query
interface. You will need to create a DBObject for the filter.

updateQuery.filter("rs elem", BasicDBObjectBuilder.start("_id",
objId).push("I").add("$nin",
Collections.singletonList(127)).pop().get());

(it is something like that; I haven't tested that.)

>
> Thanks!

Brian KimJohnson

unread,
Feb 7, 2011, 3:37:50 PM2/7/11
to Morphia
That worked perfectly. Thanks Scott!

vermoid

unread,
Aug 6, 2012, 1:45:44 PM8/6/12
to mor...@googlegroups.com
I wanted to do elemMatch, so this example helped.
But when I run the query, I get a Throwable exception back. 

2012-08-06 10:39:04,845 [http-9002-1] WARN  com.google.code.morphia.mapping.Mapper - The type(s) for the query/update may be inconsistent; using an instance of type 'com.mongodb.BasicDBObject' for the field 'com.creative.resources.content.CreativeContainerInternal.creatives' which is declared as 'java.util.List'
2012-08-06 10:39:04,845 [http-9002-1] DEBUG com.google.code.morphia.mapping.Mapper - Location of warning:

java.lang.Throwable
at com.google.code.morphia.mapping.Mapper.validate(Mapper.java:642)
at com.google.code.morphia.query.FieldCriteria.<init>(FieldCriteria.java:30)
at com.google.code.morphia.query.QueryImpl.filter(QueryImpl.java:317)
Reply all
Reply to author
Forward
0 new messages