Reputation: 35
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;
Upvotes: 3
Views: 4977
Reputation: 43884
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.
Upvotes: 0
Reputation: 2699
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.
Upvotes: 3
Reputation: 4640
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.
Upvotes: 1