Reputation: 19
I have created a "params" collection in Mongo with the following structure:
{
"_id" : "id1",
"list" : [
{
"type" : "type1",
"subtypes" : [ "id1 subtype11", "id1 subtype12" ]
}
{
"type" : "type2",
"subtypes" : [ "id1 subtype21", "id1 subtype22" ]
}
]
}
{
"_id" : "id2",
"list" : [
{
"type" : "type1",
"subtypes" : [ "id2 subtype11", "id2 subtype12" ]
}
{
"type" : "type2",
"subtypes" : [ "id2 subtype21", "id2 subtype22" ]
}
]
}
I want to get all "subtypes"
for "_id":"id1"
and "type":"type1"
. I found out that the way to do this in the Mongo shell is
db.params.find (
{ $and: [
{"_id" : "id1"},
{"list.type" : "type1"}
] }
)
I have two questions:
Thank you!
Upvotes: 0
Views: 2729
Reputation: 1076
$collection->find(array(), array('USERS.TASKS.MISSION_SAS_ID' => true));
use this above code to get sub document data
Upvotes: 1
Reputation: 19
It turns out that the PHP code that answers this question was not that difficult, actually:
$query = array('_id' => 'id1', 'list.type' => 'type1');
$result = $collection->find($query);
/* Use this to access each element of the results */
foreach($result as $doc) {
/* Code goes here */
}
If one wants to use each value in "type"
instead (and print them all for example), the code would be:
$output = [];
$query = array('_id' => 'id1');
$field = array('list.type' => true);
$result = $collection->find($query, $field);
foreach($result as $doc) {
foreach($doc['list'] as $elem) {
$output[] = $elem['type'];
}
}
I found out all of this by using the var_dump()
function on each document and analyzing the output. Hope this helps beginners like me. Thanks to Sammaye for the tips! :)
Upvotes: 1