如何从MongoDB对象的结果中删除重复值?
我的mongodb中有一些记录如下
{"Filename":"PHP Book.pdf","Author":"John" ,"Description":"This is my PHP Book"}
{"Filename":"Java Book.html" ,"Author":"Paul" ,"Description":"This is my JAVA Book"}
{"Filename":".NET Book.doc" ,"Author":"James" ,"Description":"This is my .NET Book"}
下面是我的代码,用于搜索包含“Java”字样并显示其文件名的“文件名”和“说明”字段。
Mongo m = new Mongo("10.0.0.26", 27017) ;
DB db = m.getDB("soft") ;
DBCollection col = db.getCollection("poc") ;
BasicDBObject query = new BasicDBObject();
BasicDBObject query1 = new BasicDBObject();
String KeyWord="JAVA";
query.put("Filename", java.util.regex.Pattern.compile(KeyWord));
query1.put("Content", java.util.regex.Pattern.compile(KeyWord));
DBCursor cursor = col.find(query) ;
DBCursor cursor1 = col.find(query1) ;
while (cursor.hasNext()) {
DBObject o = cursor.next();
System.out.println("File name contains JAVA:"+o.get("Filename"));
}
while (cursor1.hasNext()) {
DBObject ob = cursor1.next();
System.out.println("File name whose content contains JAVA:"+ob.get("Filename"));
}
我得到以下输出:
File Name Contains JAVA:Java Book.html
File Name whose content Contains JAVA:Java Book.html
我从文件名和内容查询中获取相同的文件名。我想删除重复的值。请建议我。
感谢
答案 0 :(得分:0)
我建议使用$或查询,例如:
DBObject query = QueryBuilder.start().or(
new BasicDBObject("Filename", java.util.regex.Pattern.compile(KeyWord)),
new BasicDBObject("Content", java.util.regex.Pattern.compile(KeyWord))).get();
并将其作为单个查询而不是两个单独的查询。
请注意,MongoDB将无法使用非锚定正则表达式的索引。有关详细信息,请参阅http://docs.mongodb.org/manual/reference/operator/regex/。