Can't access values in MongoDB with cursor using PHP
I seem to 开发者_运维百科be having some trouble using the cursor as I try to pull data out of a MongoDB. Here is a screenshot of my simple data structure:
data structure screenshot http://droplr.com/IpcH+
I'm trying to use the following:
$collection_name = "users";
$collection = $this->mongo->db->$collection_name;
$which_document = array("email" => $email_address);
$which_fields = array("words");
$cursor = $collection->find($which_document, $which_fields);
But my $cursor does not seem to be going any further into the document than the actual document. In the end, I'm looking to sort() and limit() on the created_at field within the "words" field, but I seem to be at an impasse here. And either MongoDB's error passing isn't very helpful, or I've no idea how to use it properly. (I'd assume the latter.)
One idea: I'm not sure the "words" table being generated inside of square brackets is correct, but here is the code I'm using to insert data here:
function create_word($word, $email_address){
$collection = 'users';
// make sure word isn't null
if($word !== NULL){
// add new data to the 'words' set
$new_data = array('$addToSet' => array('words' => array(
'word' => $word,
'status' => 'open',
'created_at' => time()
)));
$this->mongo->db->$collection->update(array('email' => $email_address), $new_data);
}
Thanks so much for any help you can give!
You can't sort subdocuments. You need to do it on the client side. In your case retrieve the words array:
$array = iterator_to_array($cursor);
$words = $array[0]["words"];
and then use php to sort the values.
Try
$collection->find(array($which_document, $which_fields))->sort(array("words.created_at" => -1));
精彩评论