简体   繁体   中英

How to write a MongoDB aggregate query in java

I don't know how to write this query in java

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

i tried to divide it into documents then aggregate them like this:

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();

but it returns null iterator what can i do to solve this problem ?

simply i changed the query of the $regex as :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM