我在一个名为GOT的mongo db集合中有几个以下的json文档,我想索引GOT集合中每个文档中的嵌套数组metaTag数组元素。
我尝试了以下内容:
BasicDBObject index = new BasicDBObject("season.questions.questionEntry.metaTags",1);
mongoColl.createIndex(index);
我不确定这个点符号是否是正确识别MY json文档中的元素以进行索引的方法? 如何判断索引是否已成功创建?
编辑:添加了我的查询:
// Query our collection documents metaTag elements for a matching string
// @SuppressWarnings("deprecation")
public void queryMetaTags(String query)
{
// Query to search all documents in current collection
List<String> continentList = Arrays.asList(new String[]{query});
DBObject matchFields = new
BasicDBObject("season.questions.questionEntry.metaTags",
new BasicDBObject("$in", continentList));
DBObject groupFields = new BasicDBObject( "_id", "$_id").append("questions",
new BasicDBObject("$push","$season.questions"));
//DBObject unwindshow = new BasicDBObject("$unwind","$show");
DBObject unwindsea = new BasicDBObject("$unwind", "$season");
DBObject unwindepi = new BasicDBObject("$unwind", "$season.questions");
DBObject match = new BasicDBObject("$match", matchFields);
DBObject group = new BasicDBObject("$group", groupFields);
@SuppressWarnings("deprecation")
AggregationOutput output =
mongoColl.aggregate(unwindsea,unwindepi,match,group);
String jsonString = null;
JSONObject jsonObject = null;
jsonResultsArray = null;
ourResultsArray = new ArrayList<JSONObject>();
// Loop for each document in our collection
for (DBObject result : output.results())
{
try
{
// Parse our results so we can add them to an ArrayList
jsonString = JSON.serialize(result);
jsonObject = new JSONObject(jsonString);
jsonResultsArray = jsonObject.getJSONArray("questions");
// Put each of our returned questionEntry elements into an ArrayList
for (int i = 0; i < jsonResultsArray.length(); i++)
{
System.out.println("jsonResultsArray element (" + i + "): " + jsonResultsArray.getJSONObject(i).toString());
ourResultsArray.add(jsonResultsArray.getJSONObject(i));
//System.out.println("ourResultsArray element (" + i + "): " + ourResultsArray.get(i).toString());
}
}
catch (JSONException e1)
{
e1.printStackTrace();
}
}
}
答案 0 :(得分:1)
您可以使用以下Java代码来索引所需的密钥:
Mongo mongo = new Mongo("localhost", 27017);
DB db = mongo.getDB("dbName"); //set dbname name here
DBCollection collection = db.getCollection("collectionName");
collection.createIndex(new BasicDBObject("season.questions.questionEntry.metaTags",1));
Here是有关索引的详细信息。