我在mongodb集合"Contact“中有以下文档结构。有一个名为“numbers”的子文档数组:
{
"name" : "Bill",
"numbers" : [
{
"type" : "home",
"number" : "01234",
},
{
"type" : "business",
"number" : "99099"
},
{
"type" : "fax",
"number" : "77777"
}
]
}当我只想查询"home“和"business”号码时,我可以在mongodb-shell中这样做:
db.Contact.find({ numbers: { $elemMatch: {
type : { $in : ["home", "business"]},
number: { $regex : "^012" }
}}});但是如何在morphia中做到这一点呢?有什么办法吗?
我知道在morphia中支持"$elemMatch“。所以我可以这样做:
query.filter("numbers elem", ???);但是,我到底如何为子文档添加组合查询呢?
发布于 2015-04-23 17:08:16
为时已晚,但也许其他人会发现它很方便。
我找到了解决方案https://groups.google.com/forum/#!topic/morphia/FlEjBoSqkhg
query.filter("numbers elem",
BasicDBObjectBuilder.start()
.push("type").add("$in", new String[]{"home", "business"}).pop()
.push("number").add("$regex", "^012").pop().get());发布于 2013-10-13 18:49:17
考虑使用jongo,而不是使用morphia。它允许您像使用MongoDB外壳一样查询MongoDB。此外,它将在映射数组元素时为您提供更大的自由度。以下是您的示例使用jongo时的外观:
contacts_collection.find("{numbers : {$elemMatch: {
type: {$in :#},
number: {$regex: #}
}
}
}",
new String[]{"home", "business"}, "^012")
.as(Contact.class);请注意,如果只需要数组中的一个(或多个) number对象,则可以使用自定义的结果映射器/处理程序。您只需将.as(Contact.class)替换为:
.map(new ResultHandler<Number>() {...}) 有关完整的示例,请查看my blog post或my GitHub repository
https://stackoverflow.com/questions/18510593
复制相似问题