2017-10-04 50 views
0

無法在mongo數據庫中查找嵌套數組中的元素。我正在使用mongo java驅動程序。註釋文件中有嵌入文件。指定春季嵌套數組的查詢條件

我的動機是檢查傳遞的ID是否在回覆文檔中存在的upvotes列表中可用。以下是json響應列表。

{ 
"_id" : ObjectId("59d3a5bf8cffc24e747b63ea"), 
"_class" : "com.forum.api.domain.Comments", 
"pageId" : "59d20dce5a7baa0d38643590", 
"comment_data" : "densghgfhng", 
"name" : "Karthe", 
"upvotes" : [ 
    "59ce67c55c942046a0931dde" 
], 
"downvotes" : [], 
"totalUpvotes" : 1, 
"totalDownvotes" : 0, 
"created_by" : "[email protected]", 
"created_date" : ISODate("2017-10-03T14:59:11.799Z"), 
"last_modified_by" : "[email protected]", 
"last_modified_date" : ISODate("2017-10-03T14:59:11.799Z"), 
"replies" : [ 
    { 
     "_id" : "vxfddsg", 
     "content" : "Commented by solludhana1", 
     "createdDate" : ISODate("2017-10-04T14:08:30.374Z"), 
     "upvotes" : [], 
     "downvotes" : [], 
     "userName" : "Karthe" 
    } 
] 

}

我已經寫了下面的Java代碼找到的元素。

Query query = new Query(); 
     new Query(new Criteria().andOperator(
       Criteria.where("_id").is("59d3a5bf8cffc24e747b63ea"), 
       Criteria.where("replies.id").is("vxfddsg").elemMatch(Criteria.where("replies.upvotes").in("1002")))); 
     Comments comments = mongoOps.findOne(query, Comments.class); 
if(comments==null){ 
} 

空塊沒有得到執行,執行進行到方法結束。我需要知道查詢的內容是否正確。

回答

0

您的查詢不正確。

使用

Query query = new 
    Query(    
    Criteria.where("_id").is("59d3a5bf8cffc24e747b63ea").and 
    ("replies") 
     .elemMatch 
      (Criteria.where("_id").is("vxfddsg").and 
      ("upvotes").in("1002") 
    ) 
); 

應該翻譯成下面的查詢

{ "_id" : {"$oid" : "59d3a5bf8cffc24e747b63ea"}, 
    "replies" : 
    { "$elemMatch" : 
     { "_id" : "vxfddsg" , "upvotes" : { "$in" : [ "1002"]}} 
    } 
}