匹配 MongoDB 陣列中的元素?


你可以使用 $or 運算子和 limit(1) 來匹配陣列中的元素。我們首先建立一個包含文件的集合 -

> db.matchElementInArrayDemo.insertOne(
...   {
...      "StudentName" : "Chris" ,
...      "StudentOtherDetails" :
...      [
...         {"StudentCountryName" : "US" , "StudentSkills" : "MongoDB"},
...         {"StudentCountryName" : "UK" , "StudentSkills" : "Java"}
...       ]
...   }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd423282cba06f46efe9ee2")
}
> db.matchElementInArrayDemo.insertOne(
...   {
...      "StudentName" : "Chris" ,
...      "StudentOtherDetails" :
...      [
...         {"StudentCountryName" : "AUS" , "StudentSkills" : "PHP"},
...         {"StudentCountryName" : "US" , "StudentSkills" : "MongoDB"}
...      ]
...   }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd423412cba06f46efe9ee3")
}

這是使用 find() 方法從集合中顯示所有文件的查詢 -

> db.matchElementInArrayDemo.find().pretty();

這會產生以下輸出 -

{
   "_id" : ObjectId("5cd423282cba06f46efe9ee2"),
   "StudentName" : "Chris",
   "StudentOtherDetails" : [
      {
         "StudentCountryName" : "US",
         "StudentSkills" : "MongoDB"
      },
      {
         "StudentCountryName" : "UK",
         "StudentSkills" : "Java"
      }
   ]
}
{
   "_id" : ObjectId("5cd423412cba06f46efe9ee3"),
   "StudentName" : "Chris",
   "StudentOtherDetails" : [
      {
         "StudentCountryName" : "AUS",
         "StudentSkills" : "PHP"
      },
      {
         "StudentCountryName" : "US",
         "StudentSkills" : "MongoDB"
      }
   ]
}

以下是 MongoDB 中匹配陣列元素的查詢 -

> db.matchElementInArrayDemo.find( { $or : [ {"StudentOtherDetails.StudentCountryName": "US" } ,{"StudentOtherDetails.StudentSkills": "MongoDB" } ] } ).limit(1);

這會產生以下輸出 -

{ "_id" : ObjectId("5cd423282cba06f46efe9ee2"), "StudentName" : "Chris", "StudentOtherDetails" : [ { "StudentCountryName" : "US", "StudentSkills" : "MongoDB" }, { "StudentCountryName" : "UK", "StudentSkills" : "Java" } ] }

更新於: 2019 年 7 月 30 日

248 次瀏覽

開啟您的職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.