2016-02-04 47 views
1

我在Morphia創建聚合時遇到了問題,documentation真的不清楚。這是原始查詢:Mongorphb Morphia聚合

db.collection('events').aggregate([ 
    { 
    $match: { 
     "identifier": { 
     $in: [ 
      userId1, userId2 
     ] 
     }, 
     $or: [ 
     { 
      "info.name": "messageType", 
      "info.value": "Push", 
      "timestamp": { 
      $gte: newDate("2015-04-27T19:53:13.912Z"), 
      $lte: newDate("2015-08-27T19:53:13.912Z") 
      } 
     } 
     ] 
    }{ 
     $unwind: "$info" 
    }, 
    { 
     $match: { 
     $or: [ 
      { 
      "info.name": "messageType", 
      "info.value": "Push" 
      } 
     ] 
     } 
    ]); 

唯一的例子在他們的文檔使用並有一些例子here但我不能讓它工作。

我沒連上了過去的第一場比賽,這是我有:

ArrayList<String> ids = new ArrayList<>(); 
      ids.add("199941"); 
      ids.add("199951"); 
    Query<Event> q = ads.getQueryFactory().createQuery(ads); 
    q.and(q.criteria("identifier").in(ids)); 
    AggregationPipeline pipeline = ads.createAggregation(Event.class).match(q); 
Iterator<Event> iterator = pipeline.aggregate(Event.class); 

一些幫助或指導,以及如何開始與查詢或者它是如何工作將是巨大的。

回答

1

您需要創建查詢match()管道通過將您的代碼拆分成易於管理的部分。所以讓我們開始 與查詢匹配的標識符字段,你已經完成了迄今爲止。我們需要結合查詢的$or部分。

從你離開凡經營,創建完整的查詢爲:

Query<Event> q = ads.getQueryFactory().createQuery(ads); 
Criteria[] arrayA = { 
    q.criteria("info.name").equal("messageType"), 
    q.criteria("info.value").equal("Push"), 
    q.field("timestamp").greaterThan(start); 
    q.field("timestamp").lessThan(end); 
}; 

Criteria[] arrayB = { 
    q.criteria("info.name").equal("messageType"), 
    q.criteria("info.value").equal("Push") 
}; 

q.and(
    q.criteria("identifier").in(ids), 
    q.or(arrayA) 
); 

Query<Event> query = ads.getQueryFactory().createQuery(ads); 
query.or(arrayB); 

AggregationPipeline pipeline = ads.createAggregation(Event.class) 
            .match(q) 
            .unwind("info") 
            .match(query); 
Iterator<Event> iterator = pipeline.aggregate(Event.class); 

以上是未經測試,但將引導您走得更近家,所以做一些必要的調整,在適當情況下。對於一些參考,下面的SO問題可能會給你一些指點:

  1. Complex AND-OR query in Morphia
  2. Morphia query with or operator

,當然還有AggregationTest.java Github的頁面

+0

非常感謝,我能創建查詢。我有一個問題是arrayB聲明'q.criteria'中的'q'變量應該替換爲'query.criteria'。如果不是爲什麼? – Jimmy