Is there any way to update nested documents by id or some other field?
I use “Full Tree in Single Document” and don’t know beforehand how deep nesting can go. Need to Update, for example, answer with {id:’104′}. I can do that via ‘dot notation’, but since I don’t know the level (depth) of nesting I can’t predict how long my 'comment.answers.answers....answers.' can go.
Is there any way to directly find and update id:’104′, or I still need to pass some kind of depth mark?
{
title:'some title',
comment:
{
id:'101'
author:'Joe',
text:'some comment',
answers:
[
{
id:'102'
author:'Joe',
text:'first answer to comment',
answers:
[
{
id:'103'
author:'Done',
text:'first answer to first answer to comment',
answers:[]
},
{
id:'104'
author:'Bob',
text:'Second answer to first answer to comment',
answers:[]
}
]
},
{
},
{
},
]
}
}
In short there’s no really good way to do a query of this sort. There are a few options:
You can create a query with a long
$orstatement, specifying each of the possible nested locations for the document:For more information about the $or operator see the docs.
In truth, the better and more sustainable solution would be to use a different schema, where all comments and answers are stored in a flat array and then store information about the relationships between the comments in a
comments.parentfield. For example:For additional options and a more in depth discussion of possible ways of modeling comment hierarchies, view the Storing Comments Use Case in the MongoDB documentation.
There are also a number of also strategies in the Trees in MongoDB that you might want to consider.