Frage

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:

  1. Am I using $and (read: "am I creating the query") the correct way?
  2. How to parse this query to PHP code properly? I get lost with the syntax :(.

Thank you!

War es hilfreich?

Lösung

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! :)

Andere Tipps

$collection->find(array(), array('USERS.TASKS.MISSION_SAS_ID' => true));

use this above code to get sub document data

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top