我在Mongo db中有以下json文档。 show元素将有几个季节元素,它们也有几个剧集元素,而这些元素又有多个questionEntry元素。
private DB mongoDatabase;
private DBCollection mongoColl;
private DBObject dbObject;
// Singleton class
// Create client (server address(host,port), credential, options)
mongoClient = new MongoClient(new ServerAddress(host, port),
Collections.singletonList(credential),
options);
mongoDatabase = ClientSingleton.getInstance().getClient().getDB("MyDB");
queryMetaTags("Season 1");
//@SuppressWarnings("deprecation")
public void queryMetaTags(String query)
{
List<String> continentList = Arrays.asList(new String[]{query});
DBObject matchFields = new
BasicDBObject("show.season.questions.questionEntry.metaTags",
new BasicDBObject("$in", continentList));
DBObject groupFields = new BasicDBObject( "_id",
"$_id").append("questions",
new BasicDBObject("$push","$show.season.questions"));
//System.out.println("2");
DBObject unwindshow = new BasicDBObject("$unwind","$show");
DBObject unwindsea = new BasicDBObject("$unwind", "$show.season");
DBObject unwindepi = new BasicDBObject("$unwind",
"$show.season.questions");
DBObject match = new BasicDBObject("$match", matchFields);
DBObject group = new BasicDBObject("$group", groupFields);
@SuppressWarnings("deprecation")
AggregationOutput output =
mongoColl.aggregate(unwindshow,unwindsea,unwindepi,match,group);
String s = JSON.serialize(dbObject);
JSONObject json = null;
for (DBObject result : output.results())
{
System.out.println(result);
// pretty view for testing
try
{
json = new JSONObject(result);
System.out.println(json.toString(4));
}
catch (JSONException e1)
{
e1.printStackTrace();
}
}
System.out.println("In end of queryMetaTags");
}
我已经能够返回questionElement(s),其中questionElements metaTag条目等于我的搜索。例如。如果metaTag元素等于我的字符串,则返回metaTag元素所在的questionEntry元素,并搜索整个show元素并使用以下代码返回所有匹配: (感谢Yathish Manjunath对这段代码的帮助)
{{1}}
我想像上面一样搜索,但只返回10个随机匹配的questionEntry元素?实现这一目标的最佳和最有效的方法是什么?
我不得不说我对搜索任何数据库的查询都是全新的,并且无法弄清楚如何实现一个灵活的解决方案?希望有人可以帮助解决这个问题。
答案 0 :(得分:1)