从mongodb中检索所有匹配记录取决于多个条件

时间:2015-08-03 10:14:05

标签: java mongodb nosql

我的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"}
      ] 
    } 

我想使用java驱动程序从 sid = 11 形状如%r%中检索记录。 我使用了以下代码,但它只给我第一条记录,请告诉我我做错了什么?

            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());
            }

1 个答案:

答案 0 :(得分:1)

使用mongo 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);
    }