ValRus
ValRus

Reputation: 119

return array item by using index in mongodb with php

I want to know how to return array item by using index in mongodb with php:

findOne(array('num[1]' => 'field_id')))

is there a way to do it?

Upvotes: 0

Views: 655

Answers (2)

Neil Lunn
Neil Lunn

Reputation: 151112

MongoDB has "dot notation" which is a bit different from the JavaScript form because this is not JavaScript:

findOne(array("num.1" => "field_id"))

Noting that array indexes are n-1 per position, so this means the "second" element of the array.

Note that this does not just return "that array item only" and is merely a query to "match" the array item at the position. If you expect only the matched item to return, then you use the positional $ operator and "projection" as well:

findOne(array("num.1" => "field_id"),array( "num.$" => 1))

Upvotes: 2

Jacobian
Jacobian

Reputation: 10802

You can do it like this:

$id = new MongoId($text_id);
$collection = $db->selectCollection ("mytable");
$doc = $collection->findOne(array('_id' => $id));
echo json_encode($doc); 

Upvotes: 0

Related Questions