我剛開始使用Mongo Db。以下是我的數據結構。如何在Mongodb中使用Java從子文檔中獲取所需的字段
它有一個skillID數組,每個數組有activeCampaigns
,每個activeCampaign
有一個callsByTimeZone
的數組。
什麼我在SQL方面尋找的是:
Select activeCampaigns.callsByTimeZone.label,
activeCampaigns.callsByTimeZone.loaded
from X
where skillID=50296 and activeCampaigns.campaign_id= 11371940
and activeCampaigns.callsByTimeZone='PT'
我所期待的輸出是讓
{"label":"PT", "loaded":1 }
我用的命令是
db.cd.find({ "skillID" : 50296 , "activeCampaigns.campaignId" : 11371940,
"activeCampaigns.callsByTimeZone.label" :"PT" },
{ "activeCampaigns.callsByTimeZone.label" : 1 ,
"activeCampaigns.callsByTimeZone.loaded" : 1 ,"_id" : 0})
的輸出我得到的是activeCampaigns.callsByTimeZone
下的所有東西,而我期待的只是PT
數據結構:
{
"skillID":50296,
"clientID":7419,
"voiceID":1,
"otherResults":7,
"activeCampaigns":
[{
"campaignId":11371940,
"campaignFileName":"Aaron.name.121.csv",
"loaded":259,
"callsByTimeZone":
[{
"label":"CT",
"loaded":6
},
{
"label":"ET",
"loaded":241
},
{
"label":"PT",
"loaded":1
}]
}]
}
我試圖在Java中一樣。
QueryBuilder query = QueryBuilder.start().and("skillID").is(50296)
.and("activeCampaigns.campaignId").is(11371940)
.and("activeCampaigns.callsByTimeZone.label").is("PT");
BasicDBObject fields = new BasicDBObject("activeCampaigns.callsByTimeZone.label",1)
.append("activeCampaigns.callsByTimeZone.loaded",1).append("_id", 0);
DBCursor cursor = coll.find(query.get(), fields);
String campaignJson = null;
while(cursor.hasNext()) {
DBObject campaignDBO = cursor.next();
campaignJson = campaignDBO.toString();
System.out.println(campaignJson);
}
獲得的值是callsByTimeZone
數組下的所有值。我目前正在解析獲得的JSON,並且只獲得PT
值。有沒有辦法查詢activeCampaigns.callsByTimeZone
中的PT
字段。
在此先感謝。如果此問題已在論壇中提出,我已經搜索了很多並未能找到合適的解決方案。 在此先感謝。
國際海事組織在Java寫mongodb查詢是真的凝灰岩! – Sikorski