[英]MongoDB Query on table with array
我有下表 DBLIST,我如何在此表上編寫與此查詢等效的內容
select databases.name,databases.host,databases.ha_map from DBLIST where "id"="DB1" and databases.dbrole="Primary";
DBLIST
{
"_id": "DB1",
"databases": [
{
"type": "Production",
"name": "Prim1",
"dbversion":"12.1.0.2.0",
"host": "Host1",
"dbrole": "Primary",
"ha_map":"Stdby1"
},
{
"type": "Production",
"name": "Stdby1",
"dbversion":"12.1.0.2.0",
"host": "host2",
"dbrole": "Standby",
"ha_map":"Prim1"
}
],
"pdba": "First Name ",
"sdba": "Last Name",
"application": "Sample Project",
"owner": "Last Name"
}
想要得到這樣的結果,(key :value ) 很好,不必是表格。
id,databases.name,databases.host,databases.ha_map DB1,Prim1,Host1,Stdby1
我會給你一步一步的示范你想要什么。
讓我們假設,我們的集合dblist
有這個條目。
{
"_id": "DB1",
"databases": [
{
"type": "Production",
"name": "Prim1",
"dbversion":"12.1.0.2.0",
"host": "Host1",
"dbrole": "Primary",
"ha_map":"Stdby1"
},
{
"type": "Production",
"name": "Stdby1",
"dbversion":"12.1.0.2.0",
"host": "host2",
"dbrole": "Standby",
"ha_map":"Prim1"
}
],
"pdba": "First Name ",
"sdba": "Last Name",
"application": "Sample Project",
"owner": "Last Name"
}
第1步
現在如果我們想在一組文檔中找到這個元素,我們可以查詢,
db.dblist.findOne({ _id: "DB1" });
此查詢將輸出上述整個文檔。
第2步
在同一個文檔中,我們有 2 個databases
條目,因為我們要找到子文檔 `dbrole: "Primary"。
db.dblist.findOne({ _id: "DB1", "databases.dbrole": "Primary" });
或者我們也可以使用, elemMatch
db.dblist.findOne({ _id: "DB1" }, { databases: { $elemMatch: { dbrole: "Primary"} } });
現在它再次輸出與我們查詢文檔相同的文檔。
第 3 步
現在我們想從中檢索一個子文檔,它是 databases 及其匹配的name
、 host
、 ha_map
。
db.dblist.findOne({ _id: "DB1" }, { databases: { $elemMatch: { dbrole: "Primary"}, "databases.name": 1, "databases.host": 1, "databases.ha_map": 1, _id: 0 } });
現在這個查詢的輸出將是,
{
"databases": [
{
"name": "Prim1",
"host": "Host1",
"ha_map": "Stdby1"
}
}
我希望這是你想要的!
所以獲得輸出的最終查詢是,
db.dblist.findOne({ _id: "DB1" }, { databases: { $elemMatch: { dbrole: "Primary"}, "databases.name": 1, "databases.host": 1, "databases.ha_map": 1, _id: 0 } });
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.