0

如何从 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

我从文件名和内容查询中获得相同的文件名。我想删除重复的值。请建议我。

谢谢

4

1 回答 1

0

我建议使用 $or 查询,例如:

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/

于 2013-07-15T18:15:20.287 回答