2015-08-03 21 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

谢谢,我得到了我的结果。 –

相关问题