简体   繁体   中英

Retrieve all match records from mongodb depend on multiple condition

I have the my mongodb collection schema in following format

    { 
    "_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"}
      ] 
    } 

And I want to Retrieve record from it where sid = 11 and shape like %r% using java driver. I used the following code but it give me only first record ,please suggest me what I doing wrong ?

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

Use mongo aggregation query as below :

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

and equivalent java code as :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM