3

I have some mongoDB documents with the following structure:

[_id] => MongoId Object (
  [$id] => 50664339b3e7a7cf1c000001
)
[uid] => 1
  [name] => Alice
  [words] => 1
  [formatIds] => Array (
        [0] => 1
        [1] => 4
  )

What I want to do is find all documents which has the value 1 in formatIds[ ]. I think it's possible to accomplish that. How can I do it in PHP?

UPDATE

Thanks for the help. It works fine now. Here is how i wrote the search,

$id=$_POST['id'];
$query = array('formatIds'=> "{$id}" );
$result = $stations_table->find($query); //where $stations_table = $db->stations;
2
  • There is a bug in you indent no ? Commented Oct 3, 2012 at 8:48
  • I dont think so.. I solved it finally.. Commented Oct 3, 2012 at 19:12

3 Answers 3

3

MongoDB treats queries on array values the same way as queries on standard values, as per the docs.

Querying for array('formatIds' => 1) should work.

Sign up to request clarification or add additional context in comments.

Comments

1

As MongoDB "transform" array into multi value for a same key :

$cursor = $mongo->base->collection->find(array('formatIds' => 1));

With correct definition of you mongo object and setting base/collection string.

Comments

0

It depends on whether you only want the documents or values that match your query or not.

If you don't mind pulling out the entire array and then searching client side for it you can of course use:

$c = $db->col->find(array('formatIds' => 1))

Since a 1-dimensional array in MongoDB can be searched like a single field.

But now to get only those that match your query since the above query will pick out all:

$db->command(array(
    'aggregate' => 'col',
    'pipeline' => array(
        array('$unwind' => "$formatIds"),
        array('$match' => array('formatIds' => 1)),
        array('$group' => array(
            '_id' => '$_id', 
            'formats' => array('$push' => '$formatIds'))
        )
    )
)

Use something like that.

This would give you a result of the _id being the _id of the document and a field of formats with only rows of the value 1 in the array.

Comments

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.