在 MongoDB 巢狀文件中設定條件?


假設我們需要找到一個值大於特定值的檔案。要執行此操作,請在巢狀文件中使用點符號,並使用 $gt 設定條件。

我們來看一個示例並建立一個包含文件的集合 -

> db.demo688.insert(
... {
... information:{id:1,details:[
...    {otherDetails:{
...       values:75
...       }
...    }
... ]
... }
... }
... )
WriteResult({ "nInserted" : 1 })
> db.demo688.insert({
... information:
... {
... id:2,
... details:
... [
...    {otherDetails:{
...       values:78
...    }
... }
... ]
... }
... }
... )
WriteResult({ "nInserted" : 1 })

使用 find() 方法從集合中顯示所有文件 -

> db.demo688.find();

這將產生以下輸出 -

{ "_id" : ObjectId("5ea57986a7e81adc6a0b3965"), "information" : { "id" : 1, "details" : [ { "otherDetails" : { "values" : 75 } } ] } }
{ "_id" : ObjectId("5ea5799ca7e81adc6a0b3966"), "information" : { "id" : 2, "details" : [ { "otherDetails" : { "values" : 78 } } ] } }

以下是訪問 MongoDB 巢狀文件的查詢 -

> db.demo688.find({"information.details.otherDetails.values":{$gt:75}});

這將產生以下輸出 -

{ "_id" : ObjectId("5ea5799ca7e81adc6a0b3966"), "information" : { "id" : 2, "details" : [ { "otherDetails" : { "values" : 78 } } ] } }

更新時間: 2020 年 5 月 14 日

290 次瀏覽

開啟你的 職業

完成課程後獲得證書

開始
廣告
© . All rights reserved.