I have a collection in MongoDB called topic
topic{
topic_title: 'thread',
reply{
reply_title: 'thread',
reply_content: 'content'
reply_created: "2013-06-18 17:54:04"
}
}
I wanted to add a reply to the topic like:
topic{
topic_title: 'thread',
reply{
reply_title: 'thread',
reply_content: 'content'
reply_created: "2013-06-18 17:54:04"
}
{
reply_title: 'reply1',
reply_content: 'reply2'
reply_created: "2013-06-18 17:57:04"
}
}
my code goes like this:
$reply = array(
"reply_title" => $title,
"reply_content" =>$content,
"reply_created" => date('Y-m-d H:i:s')
);
$document = array('$push' => array("reply" => $reply));
$id = new MongoId($topicid);
$topic->update(array("_id"=>$id),$document);
and it did something like this
topic{
topic_title: 'replytitle'
reply {
reply_title: "replytitle"
reply_content: "replycontent"
reply_created: "2013-06-18 17:57:12"
}
}
reply{
reply{
reply_title: "replytitle"
reply_content: "replycontent"
reply_created: "2013-06-18 17:57:12"
}
reply{
reply_title: "replytitle"
reply_content: "replycontent"
reply_created: "2013-06-18 17:57:12"
}
}
I am really having a hard time doing a simple thing. which is add a reply to the reply array. Any help out there?
I'm a little unclear on what your document structure is since what you posted isn't valid JSON. But assuming that topic.reply
is supposed to be an array of documents, you can use the $push
operator like this:
$topic->update( array( "_id" => $id ), array( "$push" => array( "topic.reply", $reply ) ) );