MongoDB Java Query:Pattern.compile(text)(类似'%'的SQL)结果

时间:2015-05-20 12:29:43

标签: java json mongodb rest

我正在使用Restfull webservice连接到MongoDB服务器并返回JSON。 当我正在搜索一个特定的短语时,我得到了整个JSON,而我只需要获得该JSON的某个部分,即该JSON中包含搜索短语的对象。 我正在使用:

Pattern.compile("first") ( SQL equivalent like '%' )。但它返回整个JSON。我该如何解决?

这是我的JSON:

{
    "_id" : ObjectId("553743843bf93901552383d8"),
    "name" : "Example Data", 
    "Example Array" : [ 
         {
            "_id" : ObjectId("553743843bf93901552383d9"),
            "name" : "Example Name!",
            "html" : "<div class='container'>This is first html</div>
         }, 
         {
            "_id" : ObjectId("553743843bf93901552383d9"),
            "name" : "Example Name2",
            "html" : "<div class='container'>This is second html</div>
         }
                     ]
}

和网络服务:

@GET
@Path("example/{text}/")
@Produces("application/json;charset=utf-8")
public String getText(@PathParam("text") String text){

DB db = getConnection().getDB(content);
DBCollection collection = db.getCollection(examples);

BasicDBObject matchTextSearch = new BasicDBObject("$match", new BasicDBObject("html", Pattern.compile(text)));

AggregationOutput output = collection.aggregate(matchTextSearch);
BasicDBList parts = new BasicDBList();
    for (DBObject result : output.results()) {
        parts = result;
    }

    return JSON.serialize(parts);
}

1 个答案:

答案 0 :(得分:0)

在查看您的文档和代码后,我认为您错过了放松Example Array然后使用匹配

@GET
@Path("example/{text}/")
@Produces("application/json;charset=utf-8")
public String getText(@PathParam("text") String text){

DB db = getConnection().getDB(content);
DBCollection collection = db.getCollection(examples);

DBObject unwind = new BasicDBObject("$unwind", "$Example Array");

BasicDBObject matchTextSearch = new BasicDBObject("$match", new BasicDBObject("Example Array.html", Pattern.compile(text)));

AggregationOutput output = collection.aggregate(unwind,matchTextSearch);
BasicDBList parts = new BasicDBList();
    for (DBObject result : output.results()) {
        parts = result;
    }

    return JSON.serialize(parts);
}