2016-08-18 54 views
1

在MongoDB上非常新穎,絕對沒有受過教育。MongoDB在嵌套對象KEY上尋找鍵值(JSON)

有了這個JSON結構:

{ 
"id": "123456", 
"makes": { 
    "abc": { 
     "att1": 4, 
     "att2": "fffff", 
     "att3": 46 
     }, 
    "fgh": { 
     "att1": 8, 
     "att2": "ggggg", 
     "att3": 6 
    }, 
    "rty": { 
     "att1": 3, 
     "att2": "hhhh", 
     "att3": 4 
     }, 
    "iop": { 
     "att1": 4, 
     "att2": "llll", 
     "att3": 3 
     } 
} 

}

我怎麼能查詢數據庫爲 「FGH」 做什麼呢? 我試過了:

db.<myCollection>.find({"makes":"fgh"}) 

但這不起作用。 它工作正常,如果我寫:

db.<myCollection>.find({"makes.fgh.att1":8}) 

謝謝你提前!

回答

3

當您嘗試查詢makes.fgh時,您不會對內容進行查詢,而是對結構進行查詢,因爲「fgh」不是一個值,而是一個子文檔。

db.myCollection.find({ "makes.fgh" : { $exists : true } }) 

參考見https://docs.mongodb.com/manual/reference/operator/query/exists/

以$存在搜索你可以做到這一點。

爲了整合@ chridam樂於助人的評論:

如果你只在感興趣的是子文檔,你還可以添加一個投影查找:

db.myCollection.find({ "makes.fgh" : { $exists : true }}, { "makes.fgh" : 1 }) 

看一看https://docs.mongodb.com/manual/reference/method/db.collection.find/#db.collection.find瞭解詳情。

+1

另外值得一提的是,在查詢db。 .find({「makes.fgh」:{「$ exists」:true}},{「makes.fgh」:1})之後的子文檔投影。 ' – chridam

+1

是的,沒錯。編輯答案包括這個事實。 – mtj

+0

現在開始變得更有意義了,謝謝你的幫助! – Zenigata