Mongodb文档检索

时间:2012-06-27 10:37:55

标签: java mongodb

我在java中使用Mongodb。我想要检索文档中的文档。

我正在使用此代码:

        DB db = null;
        int count = 0;

        //Enter the day for which you want to search for logged on users
        String dayToSearch = "27-06-2012"; //Enter in the format dd-MM-yyyy

        db = DatabaseConnection.getDatabaseObject();
        Set<String> colls = db.getCollectionNames();

        for (String s : colls) {

            DBCollection coll = db.getCollection(s);

            DBObject obj = coll.findOne();

            if(obj==null)
                System.out.println("This is only null.");

            DBObject obj1 = (DBObject)obj.get("LoginRequest");
            if(obj1!=null){
                String time = (String)obj1.get("Time");
                if(time==dayToSearch){
                    BasicDBObject query = new BasicDBObject();
                    query.put("LoginResponse", new BasicDBObject());
                    DBCursor cur1 = coll.find(query);
                    if(cur1.hasNext()){
                        count++;
                    }
                }
            }
            else
                System.out.println("It is null again!!!");
            System.out.println(s);
        }

        System.out.println("No.of users logged in successfully: " + count);

但是我在DBObject obj1 =(DBObject)obj.get(“LoginRequest”);获取空值。每个集合的所有obj1对象都是null。我打印了obj,它出来是正确的。但是obj1似乎是空的。

我的数据库是这种形式:

{
        "_id" : ObjectId("4fead665b79eedd6a5776f38"),
        "test" : "hi",
        "NBC Connection id" : "6f829b01382d556eaf16c34617C2",
        "LoginRequest" : {
                "Time" : "27-06-2012",
                "Model" : null,
                "Version" : null,
                "Username" : "acpptu20000",
                "Password" : "*******",
                "Language" : "en",
                "Manufacturer" : null
        }
}
{
        "_id" : ObjectId("4fead67cb79eedd6a5776f5b"),
        "GetInfoRequest" : {
                "MaxCallLogs" : 45,
                "MaxNewVoicemails" : 15,
                "GetInfoDateOptions" : 7,
                "MaxSavedVoicemails" : 15,
                "SubscribeForUpdates" : false
        }
}

1 个答案:

答案 0 :(得分:1)

我认为你的代码比需要的要复杂得多 尝试类似的事情:

        for(String s : colls)
        {
            DBCollection coll = db.getCollection(s);
            DBCursor whatIHaveBeenLookingFor = coll.find(
                new BasicDBObject().append("LoginRequest",
                new BasicDBObject().append("Time", dayToSearch)));
        }

我没有对此进行测试,因为我没有您的数据库。所以你可能有必要改变一些事情。但这就是你可以轻松从MongoDB中检索内容的方法。

P.S。:确保您必须遍历所有集合。