2016-04-05 36 views
0

海蘭,MongoDB中,爪哇 - 從JSON查詢到文檔

我需要一些幫助翻譯以下MongoDB的查詢到MongoDB的Java驅動程序查詢。

請注意查詢的工作原理。

db.days.aggregate([ 
    { $match: { 'day' : 'March_1'}}, 
    { $project: { 
     _id : 0, 
     day: 1, 
     events: {$filter: { 
      input: '$events', 
      as: 'event', 
      cond: {$eq: ['$$event.year', '2002']} 
     }} 
    }} 
]) 

我的嘗試是這樣,但它失敗了,我需要你的幫助。

Document query = new Document("$match", new Document("day", day)). 
    append("$project", new Document("_id", 0). 
      append("day", 1). 
      append("events", new Document("$filter", new Document(
        "input", "$" + category). 
        append("as", "event"). 
        append("cond", new Document("$eq", Arrays.asList("$$event.year", year)))))); 

,我得到的錯誤是

"{ "ok" : 0.0, "errmsg" : "A pipeline stage specification object must contain exactly one field.", "code" : 16435 }" 

非常感謝您!

+0

你得到什麼錯誤? – Arcath

+0

請參閱編輯。謝謝! –

+0

我認爲這是我建立一個文件而不是一個數組的問題。但我找不到使用文檔構建數組的任何內容。 –

回答

4

不要將$匹配和$項目在同一個對象,使用列表

AggregateIterable<Document> iterable = collection.aggregate(
    asList(
    new Document("$match", new Document("day", day)), 
    new Document("$project", 
     new Document("_id", "0") 
      .append("day", 1) 
      .append(
       "events", 
       new Document(
        "$filter", 
        new Document("input", "$events") 
         .append("as", "event") 
         .append(
          "cond", 
          new Document("eq", Arrays.asList("$$event.year", year)) 
         ) 
       ) 
      ) 
    ) 
    ) 
) 
+0

非常感謝!幾天前我剛剛開始使用MongoDB,並且要用Java來自殺... –