2015-08-03 27 views
1

我有我的MongoDB集合模式在以下格式檢索所有匹配記錄從MongoDB的取決於多個條件

{ 
    "_id" : 1, 
    "sid" : 11, 
    "shapes" : [ 
     {"shape" : "square", "color" : "red"}, 
     {"shape" : "circle", "color" : "green"}, 
     {"shape" : "rectangle", "color" : "green"}, 
     ......, 
     ......, 
     {"shape" : "elipse", "color" : "green"} 
     ] 
    }, 
    ........, 
    ........, 
    { 
    "_id" : 100 
    "sid" : 111, 
    "shapes" : [ 
     {"shape" : "square", "color" : "red"}, 
     {"shape" : "circle", "color" : "green"}, 

     ......, 
     {"shape" : "rectangle", "color" : "green"} 
     ] 
    } 

,我想從中檢索記錄,其中SID = 11外形似%R %使用java驅動程序。 我用下面的代碼,但它只給我第一個記錄,請告訴我我做錯了什麼?

  DBObject query = new BasicDBObject("sid", 1); 
      DBObject searchQuery = new BasicDBObject(); 
      Pattern regex = Pattern.compile(".*r.*"); 
      searchQuery.put("shape", regex); 
      DBObject elemMatchQuery = new BasicDBObject("$elemMatch", searchQuery); 

      DBObject fields = new BasicDBObject(); 
      fields.put("shapes", elemMatchQuery); 

      DBCursor cursor = collection.find(query, fields); 
      System.out.println(cursor.count()); 
      while (cursor.hasNext()) { 
       System.out.println(cursor.next()); 
      } 
+0

的[$ elemMatch](http://docs.mongodb.org/manual/reference/operator/query/elemMatch /)操作符匹配包含數組字段的文檔,其中至少有一個元素與所有指定的查詢條件匹配,因此,如果找到所有匹配的數據,上面的查詢只匹配第一個匹配的數組值[aggrega (http://docs.mongodb.org/getting-started/java/aggregation/) – Yogesh

+0

謝謝您的回覆,我是初學者,先生您能否爲我的要求提供相應的代碼。 –

回答

1

使用蒙戈aggregation查詢如下:

db.collectionName.aggregate({"$match":{"sid":11}},{"$unwind":"$shapes"},{"$match":{"shapes.shape":{"$regex":".r."}}}) 

和等價的Java代碼爲:

BasicDBObject match = new BasicDBObject("sid",11); 
    BasicDBObject firstmatchObj = new BasicDBObject(); 
    firstmatchObj.put("$match", match); 
    BasicDBObject unwind = new BasicDBObject("$unwind","$shapes"); 
    BasicDBObject matchAfterUnwind = new BasicDBObject("shapes.shape",new BasicDBObject("$regex",".r.")); 
    BasicDBObject secondmatchObj = new BasicDBObject(); 
    secondmatchObj.put("$match", matchAfterUnwind); 
    List<DBObject> pipeline = new ArrayList<>(); 
    pipeline.add(firstmatchObj); 
    pipeline.add(unwind); 
    pipeline.add(secondmatchObj); 
    AggregationOutput output = collection.aggregate(pipeline); 
    for (DBObject res : output.results()) { 
     System.out.println(res); 
    } 
+0

謝謝,我得到了我的結果。 –

相關問題