2014-09-19 112 views
0

我想只有那些在一個嵌入式document.For例如 我收集老鄉,如何排除刪除的記錄

{ 
    "users":[ 
      { 
      "email":"[email protected]"    
      "messages":[ 
         { 
          "text":"some message", 
          "isDeleted":"false" 
         },{ 
          "text":"some message", 
          "isDeleted":"false" 
         },{ 
          "text":"some message", 
          "isDeleted":"false" 
         },{ 
          "text":"some message", 
          "isDeleted":"true" 
         },{ 
          "text":"some message", 
          "isDeleted":"false" 
         } 

      ]    

      } 
    ] 

} 

所以刪除未標明消息結果應該爲4級的消息不5.

我想這

Query query = new Query(); 
query.addCriteria(Criteria.where("messages.isDeleted").is(false)); 
User user = mongoTemplate.findOne(query,User.class); 

但正如我的查詢返回的用戶,這將無法工作,當我得到我們它的消息包含所有消息。

回答

0

你需要使用$unwind運營商放鬆消息數組,然後使用$match操作

DBObject unwind = new BasicDBObject("$unwind", "$messages"); 
DBObject match = new BasicDBObject("$match", new BasicDBObject("messages.isDeleted", false)); 

AggregationOutput output = mongoTemplate.getCollection("user").aggregate(unwind, match); 
List<Message> messages = new ArrayList<Message>(); 
Iterator<DBObject> iterator = output.results().iterator(); 
while(iterator.hasNext()) { 
    DBObject obj = (DBObject) iterator.next(); 
    Message message = emrDataStore.getConverter().read(Message.class, (DBObject)obj.get("messages")); 
    messages.add(message); 
} 

List<Message> messages將持有的結果應用的條件 - 消息,這些消息不會被刪除