在我的 mongoDB 书籍收藏中,我的文档结构如下:
/* 0 */
{
"_id" : ObjectId("50485b89b30f1ea69110ff4c"),
"publisher" : {
"$ref" : "boohya",
"$id" : "foo"
},
"displayName" : "Paris Nightlife",
"catalogDescription" : "Some desc goes here",
"languageCode" : "en",
"rating" : 0,
"status" : "LIVE",
"thumbnailId" : ObjectId("50485b89b30f1ea69110ff4b"),
"indexTokens" : ["Nightlife", "Paris"]
}
我执行以下正则表达式查询以查找具有一个以 "Par" 开头的 indexToken 的所有文档:
{ "indexTokens" : { "$regex" : "^Par" , "$options" : "i"}}
如果我只选择要返回的 indexTokens 字段,如下所示:
{ "indexTokens" : 1}
生成的 DBObject 是
{ "_id" : { "$oid" : "50485b89b30f1ea69110ff4c"} , "indexTokens" : [ "Nightlife" , "Paris"]}
我想得到的只是与正则表达式匹配的令牌/标签(此时我不关心检索文档,我也不需要匹配文档的所有标签)
这是在 MongoDB v2.2 下发布的新聚合框架的情况。?
如果是,我该如何修改我的查询,以便实际结果如下所示:
{ "indexTokens" : ["Paris", "Paradise River", "Parma" 等 ....]}
额外的问题(你有 codez):我如何使用 Java 驱动程序来做到这一点?
现在我的java看起来像:
DBObject query = new BasicDBObject("indexTokens", java.util.regex.Pattern.compile("^"+filter+"", Pattern.CASE_INSENSITIVE));
BasicDBObject fields = new BasicDBObject("indexTokens",1);
DBCursor curs = getCollection()
.find(query, fields)
.sort( new BasicDBObject( "indexTokens" , 1 ))
.limit(maxSuggestionCount);
谢谢 :)
编辑:
根据您的回答,我修改了我的 JAVA 代码,如下所示:
BasicDBObject cmdBody = new BasicDBObject("aggregate", "Book");
ArrayList<BasicDBObject> pipeline = new ArrayList<BasicDBObject>();
BasicDBObject match = new BasicDBObject("$match", new BasicDBObject("indexTokens", java.util.regex.Pattern.compile("^"+titleFilter+"", Pattern.CASE_INSENSITIVE)));
BasicDBObject unwind = new BasicDBObject("$unwind", "$indexTokens");
BasicDBObject match2 = new BasicDBObject("$match", new BasicDBObject("indexTokens", java.util.regex.Pattern.compile("^"+titleFilter+"", Pattern.CASE_INSENSITIVE)));
BasicDBObject groupFilters = new BasicDBObject("_id",null);
groupFilters.append("indexTokens", new BasicDBObject( "$push", "$indexTokens"));
BasicDBObject group = new BasicDBObject("$group", groupFilters);
pipeline.add(match);
pipeline.add(unwind);
pipeline.add(match2);
pipeline.add(group);
cmdBody.put("pipeline", pipeline);
CommandResult res = getCollection().getDB().command(cmdBody);
System.out.println(res);
哪个输出
{ "result" : [ { "_id" : null , "indexTokens" : [ "Paris"]}] , "ok" : 1.0}
这是天才!
非常感谢 !