如何在巢狀陣列中提取 MongoDB 中的特定元素?


要提取 MongoDB 中的特定元素,可以使用 $elemMatch 運算子。我們首先建立一個包含文件的集合 --

> db.particularElementDemo.insertOne(
   {
      "GroupId" :"Group-1",
      "UserDetails" : [
         {
            "UserName" : "John",
            "UserOtherDetails" : [
               {
                  "UserEmailId" : "John123@gmail.com",
                  "UserFriendName" : [
                     {
                        "Name" : "Chris"
                     }
                  ]
               },
               {
                  "UserEmailId" : "John22@hotmail.com",
                  "UserFriendName" : [
                     {
                        "Name" : "Robert"
                     }
                  ]
               }
            ]
         }
      ]
   }
);
{ "acknowledged" : true, "insertedId" : 100 }
> db.particularElementDemo.find().pretty();
{
   "_id" : 100,
   "GroupId" : "Group-1",
   "UserDetails" : [
      {
         "UserName" : "John",
         "UserOtherDetails" : [
            {
               "UserEmailId" : "John123@gmail.com",
               "UserFriendName" : [
                  {
                     "Name" : "Chris"
                  }
               ]
            },
            {
               "UserEmailId" : "John22@hotmail.com",
               "UserFriendName" : [
                  {
                     "Name" : "Robert"
                  }
               ]
            }
         ]
      }
   ]
}

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

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

這將產生以下輸出 --

{
   "_id" : 100,
   "GroupId" : "Group-1",
   "UserDetails" : [
      {
         "UserName" : "John",
         "UserOtherDetails" : [
            {
               "UserEmailId" : "John123@gmail.com",
               "UserFriendName" : [
                  {
                     "Name" : "Chris"
                  }
               ]
            },
            {
               "UserEmailId" : "John22@hotmail.com",
               "UserFriendName" : [
                  {
                     "Name" : "Robert"
                  }
               ]
            }
         ]
      }
   ]
}

以下是提取 MongoDB 巢狀陣列中特定元素的查詢 --

> db.particularElementDemo.find(
   {
      'UserDetails':{
         $elemMatch:{
            'UserOtherDetails':{
               $elemMatch:{
                  'UserFriendName':{ $elemMatch: {"Name" : "Robert" } }
               }
            }
         }
      }
   },{"UserDetails.UserOtherDetails.UserFriendName.Name":1}
);

這將產生以下輸出 --

{ "_id" : 100, "UserDetails" : [ { "UserOtherDetails" : [ { "UserFriendName" : [ { "Name" : "Chris" } ] }, { "UserFriendName" : [ { "Name" : "Robert" } ] } ] } ] }

更新於:2019 年 7 月 30 日

515 次瀏覽

開啟您的事業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.