Reputation: 1809
I'm having trouble working out a morphia query. I have a schema like this:
{ authorId:12345,
comments:[
{ userId:34567,
name:"joe" },
{ userId:98765,
name:"sam" }
]
}
and I want to find all records using morphia where searchId is equal to authorId or userId.
I've tried a range of things, but I'm not getting it. E.g.
Query<Record> query = datastore.find(Record.class);
query.or(
query.criteria(authorId).equal(searchId),
query.criteria(comments).hasAnyOf(Collections.singletonList(searchId))
);
I've also tried using hasThisElement, but that didn't work either.
How do I do this?
Upvotes: 2
Views: 2018
Reputation: 103365
Because comments
is an embedded field, use the dot notation to query on the fields of an embedded document. The mongo shell query
db.records.find(
{
"$or": [
{ "authorId": searchId },
{ "comments.userId": searchId }
]
}
)
is what you need here. The Morphia equivalent would be
Datastore ds = ...
Query<Record> q = ds.createQuery(Record.class);
q.or(
q.criteria("authorId").equal(searchId),
q.criteria("comments.userId").equal(searchId)
);
//list
List<Record> entities = q.asList();
Upvotes: 5