0

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?

2 Answers 2

2

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))
Sign up to request clarification or add additional context in comments.

6 Comments

for some reason I get 'null' this way. what should I do if I want to return "comment" { "num": [ { "group": "187", "ques": "question 1", "answ": [ { "desc": "answer 1", "right": true }, { "desc": "answer 2", "right": false }, { "desc": "answer 3", "right": false }, { "desc": "answer 4", "right": false } ], "comment": "comment 1" } ] }
@ValRus Can you please show the acutal structure of your document as it appears in the mongo "shell". Because just of the content in your comment the field is not "num" but in fact "comment.num". Understand the distinct difference.
Sorry not to make it clear, the actual structure goes from { and after, the "comment" string is just what I wanted to return
@ValRus So Alter the code. You didn't ask that way so why would I answer that way? I also don't answer altered questions after I answer because I consider it extremely rude practice and regularly downvote anyone who has done that to be in the past. Just kidding but it really not an acceptable practice and it will not be looked on kindly if you change the parameters of your initial question.
You are very right, my bad is that I didn't provide full description in the first place. As you already answered, and I did try it, and it still didn't return the value. But I need it badly.
|
0

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); 

3 Comments

I think the question was asking "how to match an element in an array based on it's position". That's not what you are answering though.
Possibly, so. I'm not quite sure
Question title and attempted code make it pretty clear.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.