I am trying to add a comment to entries into mongodb.
This is what i have so far
$mongo = new Mongo();
$db = $mongo->comedy;
$collection = $db->cartoons;
$obj = array(
"title" => "football", array('comment' => 'my comment here'),
"author" => "joe"
);
$collection->insert($obj);
which produces this entry
{
"_id": ObjectId("5059fd31ba76883414000001"),
"title": "football",
"0": {
"comment": "my comment here"
},
"author": "joe"
}
my question is this the best way to nest a comment under the entry “football”? or should i be going about it a different way?
this part doesnt seem correct
"0": {
"comment": "my comment here"
}
update
from the example below, running this gave an error Fatal error: Call to undefined method MongoDB::update()
$mongo = new Mongo();
$db = $mongo->comedy;
$collection = $db->cartoons;
$mongo->comedy->update(array('title' => 'football'), array(
'$push' => array('comments' => array('content' => 'Yo!', 'author' => $user_id))
));
then when i run it like
$mongo = new Mongo();
$db = $mongo->comedy;
$collection = $db->cartoons;
$obj = array(
'$set' => array("title" => "football", "author" => "joe"),
'$push' => array('comments' => array('content' => 'Yo!'))
);
i get
{
"_id": ObjectId("505a2493ba76883c08000007"),
"title": "football",
"0": {
"$push": {
"comments": {
"content": "Yo!"
}
}
},
"author": "joe"
}
This is a very typical problem in MongoDB and as a noob it too got me once here is a good structure (you can Google this around):
You can then
$pushto the comments field making all comments be sorted from newest tooldest.
As a word of caution: You might find this schema a bit restrictive on it’s querying possibilities especially when you want to, in realtime, sort the comments a different way or pick out different types of comments. In this scenario you would use a separate collection to house the comments ideally.
Edit
In PHP you would start off by inserting your document:
And then when a new comment needs to be added just simply $push:
And that’s the simple method of doing it 🙂
Edit again