在 MongoDB 中執行巢狀文件值搜尋?


為了搜尋值,在 MongoDB 中使用 $match。讓我們建立一個帶有文件的集合 −

> db.demo648.insertOne(
...    {
...       StudentInformation:
...       [
...          {
...             Name:"John",
...             CountryName:"US"
...          },
...          {
...             Name:"David",
...             CountryName:"AUS"
...          },
...          {
...             Name:"Chris",
...             CountryName:"US"
...          },
...          {
...             Name:"Robert",
...             CountryName:"UK"
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9c8b286c954c74be91e6f5")
}

在集合中顯示所有文件,使用 find() 方法 −

> db.demo648.find();

這將生成以下輸出 −

{ "_id" : ObjectId("5e9c8b286c954c74be91e6f5"), "StudentInformation" : [
   { "Name" : "John", "CountryName" : "US" },
   { "Name" : "David", "CountryName" : "AUS" },
   { "Name" : "Chris", "CountryName" : "US" },    
   { "Name" : "Robert", "CountryName" : "UK" } 
] }

以下是 MongoDB 中搜索值的查詢 −

> db.demo648.aggregate([
...    { $unwind: "$StudentInformation" },
...    { $match: { "StudentInformation.CountryName": "US" } },
...    { $project: {_id: 0}}
... ])

這將生成以下輸出 −

{ "StudentInformation" : { "Name" : "John", "CountryName" : "US" } }
{ "StudentInformation" : { "Name" : "Chris", "CountryName" : "US" } }

更新於:2020 年 5 月 12 日

102 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告