我正在使用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);
}
答案 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);
}