【发布时间】:2019-04-12 03:15:12
【问题描述】:
我有这个在 mongodb 中运行良好的查询:
db.document.aggregate([
{$match: { $and: [
{ type:ObjectId('abc') },
{ metadata: { $elemMatch: { metadataType: ObjectId("abc"), value: DBRef("tag", ObjectId("abc"))}}},
{ metadata: { $elemMatch: { metadataType: ObjectId("abc"), value: "abc"}}}
] }
},
{$project: {
metadata: {
$filter: {
input: "$metadata",
as: "metadata",
cond: { $or: [
{$eq: [ "$$metadata.metadataType", ObjectId("abc") ] },
{$eq: [ "$$metadata.metadataType", ObjectId("abc") ] }]}
}
}
}
如何在 JAVA 中使用 mongodb 驱动程序执行此操作?我可以执行 $match 阶段,但我不知道如何使用数组的 $filter 执行 $project 阶段。
我可以使用 Document.parse() (就像这里建议的那样:https://groups.google.com/forum/#!topic/mongodb-user/W4wiPYk0Gec )但我认为它很丑陋。 或者我可以在这里使用类似的东西:Does Spring Data MongoDb support $filter array aggregations operator? 但它也不太漂亮。
基本上我的问题是:在较新版本的 mongodb 驱动程序中是否有更好/更好的方法来做到这一点? (类似于 spring mongodb 的第三个答案:Query a document and all of its subdocuments that match a condition in mongodb (using spring))
***** 编辑
更准确地说: 有没有办法像这里的比赛部分一样:
AggregateIterable<Document> output = document.aggregate(
Arrays.asList(
Aggregates.match(and(
eq("type", new ObjectId("abc")),
elemMatch("metadata", and(eq("metadataType", language), eq("value", abc))),
elemMatch("metadata", and(eq("metadataType", workClusterName), eq("value", "abc")))
)),
Aggregates.project(filterHOWTO)
));
【问题讨论】: