Reputation: 12898
Let's imagine a mongo collection of - let's say magazines. For some reason, we've ended up storing each issue of the magazine as a separate document. Each article is a subdocument inside an Articles
-array, and the authors of each article is represented as a subdocument inside the Writers
-array on the Article
-subdocument. Only the name and email of the author is stored inside the article, but there is an Writers
-array on the magazine level containing more information about each author.
{
"Title": "The Magazine",
"Articles": [
{
"Title": "Mongo Queries 101",
"Summary": ".....",
"Writers": [
{
"Name": "tom",
"Email": "[email protected]"
},
{
"Name": "anna",
"Email": "[email protected]"
}
]
},
{
"Title": "Why not SQL instead?",
"Summary": ".....",
"Writers": [
{
"Name": "mike",
"Email": "[email protected]"
},
{
"Name": "anna",
"Email": "[email protected]"
}
]
}
],
"Writers": [
{
"Name": "tom",
"Email": "[email protected]",
"Web": "tom.example.com"
},
{
"Name": "mike",
"Email": "[email protected]",
"Web": "mike.example.com"
},
{
"Name": "anna",
"Email": "[email protected]",
"Web": "anna.example.com"
}
]
}
How can one author be completely removed from a magazines?
Finding magazines where the unwanted author exist is quite easy. The problem is pulling the author out of all the sub documents.
MongoDB 3.6 introduces some new placeholder operators, $[]
and $[<identity>]
, and I suspect these could be used with either $pull
or $pullAll
, but so far, I haven't had any success.
Is it possible to do this in one go? Or at least no more than two? One query for removing the author from all the articles, and one for removing the biography from the magazine?
Upvotes: 1
Views: 632
Reputation: 75994
You can try below query.
db.col.update(
{},
{"$pull":{
"Articles.$[].Writers":{"Name": "tom","Email": "[email protected]"},
"Writers":{"Name": "tom","Email": "[email protected]"}
}},
{"multi":true}
);
Upvotes: 1