1

我在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 对象都为空。我打印了 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
        }
}
4

1 回答 1

1

我认为您的代码比需要的要复杂得多。
尝试这样的事情:

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

我没有对此进行测试,因为我没有您的数据库。因此,您可能必须更改某些内容。但这就是您可以轻松地从 MongoDB 中检索某些内容的方式。

PS:确保您确实必须遍历所有集合。

于 2012-06-27T11:41:58.307 回答