查询以从mongoDB获取结果

时间:2016-12-15 08:31:21

标签: java spring mongodb

我在MongoDB中有以下集合

 "userDetails" : [
        { 
            "user" : DBRef("users", "RAVI"), 
            "class1" : DBRef("classes", "1"), 
            "class2" : DBRef("classes", "2")
        }, 
        { 
            "user" : DBRef("users", "TEJA"), 
            "class1" : DBRef("classes", "1"), 
            "class2" : DBRef("classes", "2")
        }]

    classes
        {
          "_id" : "1",
          "maxScore" : "50",
          "subject" :  DBRef("subjects", "class1")
    }
    { 
        "_id" : "2",
          "maxScore" : "80",
          "subject" :  DBRef("subjects", "class2")
    }
    users{
    "_id" : "RAVI",
    "address" : "3-2-2222",
    "lastClass" : "1"
    "lastScore" : ""
    }
    {
    "_id" : "TEJA",
    "address" : "5-23",
    "lastClass" : "1"
    }

从java程序,我想查询,当我将输入作为用户名传递时,我想获取该用户的所有详细信息及其类详细信息。任何人都可以帮我解决这个问题吗? 以前我试过

BasicDBObject fields = new BasicDBObject("userDetails", 1).append("userDetails", new BasicDBObject("$elemMatch", new BasicDBObject("user.$id", "RAVI")));
        BasicQuery query = new BasicQuery(new BasicDBObject(), fields);
        List<UserDetails> usrDetailsList = mongoTemplate.find(query, UserDetails.class);

2 个答案:

答案 0 :(得分:0)

//Considering you have data inserted in your collection, now this following code will fetch a specific record from collection:

  BasicDBObject whereQuery = new BasicDBObject();

  whereQuery.put("user","RAVI");  //here you are specifying that you want all details of user-RAVI

  DBCursor cursor = collection.find(whereQuery);

 while(cursor.hasNext()) {
     System.out.println(cursor.next());
 }

答案 1 :(得分:0)

我的解决方案稍有改动。我在ID之前删除了$符号,我得到了答案

BasicDBObject fields = new BasicDBObject("userDetails", 1).append("userDetails", new BasicDBObject("$elemMatch", new BasicDBObject("user.id", "RAVI")));
    BasicQuery query = new BasicQuery(new BasicDBObject(), fields);
    List<UserDetails> usrDetailsList = mongoTemplate.find(query, UserDetails.class);

但我陷入了另一个问题。我想根据主题ID搜索我的查询,如下面的

BasicDBObject fields = new BasicDBObject("userDetails", 1).append("userDetails", new BasicDBObject("$elemMatch", new BasicDBObject("class1.$subject.$id", "class1")));
    BasicQuery query = new BasicQuery(new BasicDBObject(), fields);
    List<UserDetails> usrDetailsList = mongoTemplate.find(query, UserDetails.class);