我在计算吗啡查询时遇到问题。 我有一个这样的架构:
{ authorId:12345,
comments:[
{ userId:34567,
name:"joe" },
{ userId:98765,
name:"sam" }
]
}
并且我想使用 morphia 查找所有记录,其中 searchId 等于authorId 或 userId。
我已经尝试了一系列的方法,但我没有得到它。例如
Query<Record> query = datastore.find(Record.class);
query.or(
query.criteria(authorId).equal(searchId),
query.criteria(comments).hasAnyOf(Collections.singletonList(searchId))
);
我也尝试过使用 hasThisElement,但这也不起作用。
我该怎么做?
最佳答案
由于 comments
是嵌入字段,因此请使用 dot notation 查询嵌入文档的字段。 mongo shell 查询
db.records.find(
{
"$or": [
{ "authorId": searchId },
{ "comments.userId": searchId }
]
}
)
就是你所需要的。 Morphia 的等价物是
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();
关于java - 使用吗啡搜索对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33866619/