如何在java中编写MongoDB聚合查询

时间:2018-03-30 10:21:32

标签: java mongodb

我不知道如何在java中编写这个查询

db.wordsRank.aggregate ([
{$match: {word: {$regex:/engin/i} } },
{$sort:{rank:-1} }
]
)

我试图把它分成文件然后像这样汇总:

Document regQuery = new Document();
regQuery.append("$regex", "/" + "engin" + "/i");

Document wordQuery = new Document();
wordQuery.append("word", regQuery);

Document matchQuery = new Document();
matchQuery.append("$match", wordQuery);

Document rankQuery = new Document();
rankQuery.append("rank", -1);

Document sortQuery = new Document();
sortQuery.append("$sort", rankQuery);

Iterator iterDoc2=collection.aggregate(
  Arrays.asList(
          matchQuery,
          sortQuery
  )
).iterator();

但它返回null迭代器我该怎么做才能解决这个问题?

1 个答案:

答案 0 :(得分:0)

我简单地将$ regex的查询更改为:

Document regQuery = new Document();
        regQuery.append("$regex", "^(?i)" + Pattern.quote("engin"));