我有以下代码,我的目的是检索具有给定标签的文档。
String myText = "It is the first #example and is very #important";
ArrayList<String> tags = textProcessor.getTags(myText);
try {
MongoClient mongo = new MongoClient("localhost", 27017);
DB db = mongo.getDB("myFirstDatabase");
DBCollection table = db.getCollection("firstCollection");
BasicDBObject document = new BasicDBObject();
document.put("Text", myText);
document.append("tags", tags);
table.insert(document);
/**** Find and display ****/
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("tags", "#important");
DBCursor cursor = table.find(searchQuery);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
它不起作用,因为tags
是一个数组,我正在数组中搜索element
。如何直接检索具有给定标签的文档(在这种情况下为"重要"(?我知道我可以提取所有文档的所有标签,然后在循环中比较它们。但是我想直接这样做。
与此同时,我是mongodb
的新手。如果有更好的方法在数据库中插入标签(因此,它的检索更容易(,我将很高兴知道。
预先感谢
可以通过单个字符串查询来查询MongoDB列表,您应该检查textProcessor.getTags并检查MongoDB中的数据。我还建议您使用Spring-Data-MongoDB,因为它更容易学习。