This is the documents format:
{
"_id" : ObjectId("123")
"types" : [ "PHONE", "ADDRESS" ]
},
{
"_id" : ObjectId("345")
"types" : [ "PHONE" ]
},
{
"_id" : ObjectId("567")
"types" : [ "PHONE", "NAME" ]
}
And this is the query to find elements which contains certain types:
public List<MyCollection> findByType(Type type) {
return getDatastore().createQuery(MyCollection.class)
.field("types").hasThisElement(type.toString())
.asList();
}
With this code, I get this error:
com.mongodb.MongoException: Can't canonicalize query: BadValue $elemMatch needs an Object
I tried using hasThisOne
method, but always returns an empty array.
How can I do this query?
Why are you using a type.toString()
?
I'd assume you have a List<Type> types
in your entity, right? Then the query should use the enum as well and not its string representation.
And you can probably use:
getDatastore().createQuery(MyCollection.class)
.field("types").equal(type).asList();
Yes, even for arrays.