從 MongoDB 中與條件匹配的多個子文件中獲取欄位?


若要從多個子文件獲取欄位,請結合 $ unwind 使用 MongoDB aggregate。讓我們建立一個包含文件的集合——

> db.demo671.insertOne(
... {
...
...    "details" : [
...    {
...       "id" : "1"
...    },
...    {
...       CountryName:"US",
...       "details1" : [
...       {
...       "id" : "1"
...       },
...       {
...          "id" : "2"
...       }
...       ]
...    },
... {
...    CountryName:"UK",
...    "details1" : [
...    {
...       "id" : "2"
...    },
...    {
...       "id" : "1"
...    }
...    ]
... },
... {
...    CountryName:"AUS",
...    "details1" : [
...       {
...          "id" : "1"
...       }
...       ]
...    }
... ]
... }
... )
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea3e5d004263e90dac943e0")
}

使用 find() 方法從某個集合顯示所有文件——

> db.demo671.find();

這將產生以下輸出——

{ "_id" : ObjectId("5ea3e5d004263e90dac943e0"), "details" : [ { "id" : "1" }, { "CountryName" : "US", "details1" : [ { "id" : "1" }, { "id" : "2" } ] }, { "CountryName" : "UK", "details1" : [ { "id" : "2" }, { "id" : "1" } ] }, { "CountryName" : "AUS", "details1" : [ { "id" : "1" } ] } ] }

以下是如何從 MongoDB 中與條件匹配的多個子文件獲取欄位的查詢——

> db.demo671.aggregate([
...
...   {$unwind: '$details'},
...
...   {$match: {'details.details1.id': '1'}},
...
...   {$project: {_id: 0, Country: '$details.CountryName'}}
... ]).pretty()

這將產生以下輸出——

{ "Country" : "US" }
{ "Country" : "UK" }
{ "Country" : "AUS" }

更新於:13-May-2020

612 瀏覽量

開啟你的 職業生涯

透過完成本課程獲得認證

入門
廣告
© . All rights reserved.