gpt4 book ai didi

java - Mongodb文档检索

转载 作者:太空宇宙 更新时间:2023-11-04 08:11:03 25 4
gpt4 key购买 nike

我在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
}
}

最佳答案

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

        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.:确保您确实必须迭代所有集合。

关于java - Mongodb文档检索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11224323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com