簡體   English   中英

從子文檔數組中的數組中刪除子文檔

[英]Delete sub-document from array in array of sub documents

讓我們想象一下-假設是雜志的mongo集合。 由於某種原因,我們最終將每期雜志都存儲為單獨的文檔。 每篇文章都是Articles數組內的子文檔,每篇文章的作者都表示為Article子文檔上Writers -array內的子文檔。 只有名稱和作者的電子郵件存儲在里面的文章,但有一個Writers含每位作者的詳細信息,該雜志的水平-陣列。

{
   "Title": "The Magazine",
   "Articles": [
     {
       "Title": "Mongo Queries 101",
       "Summary": ".....",
       "Writers": [
         {
           "Name": "tom",
           "Email": "tom@example.com"
         },
         {
           "Name": "anna",
           "Email": "anna@example.com"
         }
        ]
     },
     {
       "Title": "Why not SQL instead?",
       "Summary": ".....",
       "Writers": [
         {
           "Name": "mike",
           "Email": "mike@example.com"
         },
         {
           "Name": "anna",
           "Email": "anna@example.com"
         }
        ]         
      }
   ],
  "Writers": [
     {
       "Name": "tom",
       "Email": "tom@example.com",
       "Web": "tom.example.com"
     },
     {
       "Name": "mike",
       "Email": "mike@example.com",
       "Web": "mike.example.com"
     },
     {
       "Name": "anna",
       "Email": "anna@example.com",
       "Web": "anna.example.com"
     }
   ]
}

如何將一位作者從雜志中徹底刪除?

在不想要的作者存在的地方查找雜志非常容易。 問題是將作者從所有子文檔中撤出。

MongoDB 3.6引入了一些新的占位符運算符$[]$[<identity>] ,我懷疑它們可以與$pull$pullAll ,但是到目前為止,我還沒有取得任何成功。

一口氣可以做到嗎? 或至少不超過兩個? 一種查詢是從所有文章中刪除作者,另一種查詢是從雜志中刪除傳記?

您可以嘗試下面的查詢。

db.col.update(
  {},
  {"$pull":{
    "Articles.$[].Writers":{"Name": "tom","Email": "tom@example.com"},
    "Writers":{"Name": "tom","Email": "tom@example.com"}
  }},
  {"multi":true}
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM