Consider the following document:
{
"comments": [
{
"id" : 1,
"userid": "john",
"comment": "lorem ipsum...",
"responses": [
{
"id" : 2,
"userid": "smith",
"comment": "lorem ipsum...",
"responses": [
{
"id" : 3,
"userid": "random",
"comment": "lorem ipsum...",
"responses": [] // I want to push a comment into this array
},
{
"id" : 4,
"userid": "guy",
"comment": "lorem ipsum..."
}
]
},
{
"id" : 5,
"userid": "adam",
"comment": "lorem ipsum..."
}
]
}
]
}
Is there ANY way to push a document into that responses array? So in this case a user wants to comment on a level-3 comment and I want to push that comment into the array. I could send the array positions to the user and back to the server when commenting but I'm pretty sure that's unreliable. Also if a delete would happen in between then (I guess(?)) the positions would change in the array, so it's really a no-go.
-
Anytime I need to update/edit a document I use Robomongo. Its quick and easygpullen– gpullen2014年11月04日 15:19:21 +00:00Commented Nov 4, 2014 at 15:19
-
Well that doesn't really solve my problem.Andrew– Andrew2014年11月04日 15:56:58 +00:00Commented Nov 4, 2014 at 15:56
-
Do you need to update the document by writing a command?gpullen– gpullen2014年11月04日 15:58:43 +00:00Commented Nov 4, 2014 at 15:58
-
I need to update the document automatically on the backend in Go.Andrew– Andrew2014年11月04日 16:00:53 +00:00Commented Nov 4, 2014 at 16:00
-
do all comments have globally unique IDs, regardless of where they sit in the nesting level?code_monk– code_monk2014年11月04日 17:34:31 +00:00Commented Nov 4, 2014 at 17:34
1 Answer 1
If you know the sequence of indexes to get down to that level, then yes:
> db.test.update({ ... }, { "$push" : { "comments.0.responses.0.responses.0.responses" : "this is my response" } })
The 0's are the indexes. However, a multiply nested structure like this is almost certainly a bad data modeling choice. You should consider other options. Perhaps the docs on modeling tree structures will be helpful?