2017-04-26 65 views
0

我在MongoDB中有一个集合processedClickLog。

{ 
     "_id" : ObjectId("58ffb4cefbe21fa7896e2d73"), 
     "ID" : "81a5d7f48e5df09c9bc006e7cc89d6e6", 
     "USERID" : "206337611536", 
     "DATETIME" : "Fri Mar 31 17:29:34 -0400 2017", 
     "QUERYTEXT" : "Tom", 
     "DOCID" : "www.demo.com", 
     "TITLE" : "Harry Potter", 
     "TAB" : "People-Tab", 
     "TOTALRESULTS" : "1", 
     "DOCRANK" : 1 
} 
{  "id": 
     .... 
} 

我想在java中执行一个复杂的查询。我的查询是让processedClickLog集合,其中

  1. TAB不等于人民-Tab键
  2. DOCRANK不等于0
  3. 仅返回 “USERID”, “DOCID”, “DOCRANK”,“QUERYTEXT “田
  4. 集团通过USERID

下面是我的Java代码。我能够满足前三个条件。但是我卡在由USERID组成的第四个条件。

String jsonResult = ""; 
     MongoClient mongoClient = new MongoClient("localhost", 27017); 
     MongoDatabase database = mongoClient.getDatabase("test1"); 
     MongoCollection<Document> collection = database.getCollection("processedClickLog"); 
     //add condition where TAB is not equal to "People-Tab" and DOCRANK is not equal to 0 
     List<DBObject> criteria = new ArrayList<DBObject>(); 
     criteria.add(new BasicDBObject("DOCRANK", new BasicDBObject("$ne", 0))); 
     criteria.add(new BasicDBObject("TAB", new BasicDBObject("$ne", "People-Tab"))); 

      //combine the above two conditions 
      BasicDBObject query = new BasicDBObject("$and", criteria); 
      //to retrieve all the documents with specific fields 
      MongoCursor<Document> cursor = collection.find(query) 
        .projection(Projections.include("USERID", "DOCID", "DOCRANK", "QUERYTEXT")).iterator(); 
     try { 
       while (cursor.hasNext()) { 
        System.out.println(cursor.next().toJson()); 

       } 
      } finally { 
       cursor.close(); 
      } 
      System.out.println(hashMap); 
      mongoClient.close(); 
    } 

我应该如何定义我的整个查询来在java中添加条件“group by USERID”?任何帮助表示赞赏

回答

1

你必须使用聚合框架。静态导入helper类的所有方法并使用下面的代码。

在较新的3.x驱动程序api中不需要使用BasicDBObject。对于类似的需求,您应该使用新类Document

import static com.mongodb.client.model.Accumulators.*; 
import static com.mongodb.client.model.Aggregates.*; 
import static java.util.Arrays.asList; 
import static com.mongodb.client.model.Filters.*; 
import static com.mongodb.client.model.Projections.*; 

Bson match = match(and(ne("DOCRANK", 0), ne("TAB", "People-Tab"))); 
Bson group = group("$USERID", first("USERID", "$USERID"), first("DOCID", "$DOCID"), first("DOCRANK", "$DOCRANK"), first("QUERYTEXT", "$QUERYTEXT")); 
Bson projection = project(fields(include("USERID", "DOCID", "DOCRANK", "QUERYTEXT"), excludeId())); 
MongoCursor<Document> cursor = collection.aggregate(asList(match, group, projection)).iterator(); 

投影阶段是可选的,只是添加了一个完整的例子。

更多关于这里聚合https://docs.mongodb.com/manual/reference/operator/aggregation/

+0

谢谢。我会试试这个,让你知道 – Rose

+0

像魅力一样工作。非常感谢 – Rose

+0

你能简单解释一下这个小组的一部分吗?我在参考链接中没有找到与此相关的任何内容。 – Rose