Ankur
Ankur

Reputation: 51138

Match objects that have a list containing a particular String With Morphia

Imagine I have a class called SomeClass which has a list of Strings called aStringList.

public Class SomeClass{

  List<String> aStringList;

  ...

}

I want to find all the objects of SomeClass such that aStringList contains a String "sillyString".

I have tried:

Datastore ds = Dao.instance().getDatabase();
List<String> myResults = ds.find(SomeClass.class).
field("aStringList").hasThisElement("sillyString").asList();

However that gives me the error:

com.mongodb.MongoException: invalid parameter: expected an object ($elemMatch)

Upvotes: 4

Views: 2176

Answers (1)

xeraa
xeraa

Reputation: 10859

Use field(...).equal(...) (assuming you are looking for an exact match). MongoDB will match both single values as well as any value inside an array.

Use .hasThisElement(...) if you have a list of custom document entities (@Reference List<MyEntity>) and you want to check if a specific one is being referenced.

Upvotes: 4

Related Questions