psychok7
psychok7

Reputation: 5473

PHP MongoDB query dynamic values

I want to query the content (text) inside my dynamic values keys, but i can't figure out the easiest way to do this.

So my mongo collection is like this:

{
    "_id" : ObjectId("566aecb8f0e46491068b456c"),
    "metadatas" : [
        {
            "schema_id" : "f645fabef0e464e51e8b4567",
            "values" : {
                "name" : "Test",
                "age" : NumberLong(29),
                "address" : "Test1"
            },
            "updated_on" : ISODate("2015-12-11T00:00:00Z")
        },
        {
            "schema_id" : "d745fabef0e464e51e8b4567",
            "values" : {
                "something_else" : "lipsum"
            },
            "updated_on" : ISODate("2016-12-11T00:00:00Z")
        }
    ],
}

How can i dynamically query whats inside my values since i cannot do $db->collec->find(array('metadatas.values.name' => $regex)) because i might have some other dynamic key instead of name?

thanks in advance

Upvotes: 0

Views: 580

Answers (1)

psychok7
psychok7

Reputation: 5473

I ended up saving my keys uniquely on another collection and then building the query and concatenating it before applying based on @Sammaye idea:

    $regex = new \MongoRegex("/^$query/i");

    # First get all the dynamic keys you need to filter
    $keys_to_search = $this->db->metadata_keys->find();
    $this->log($keys_to_search);

    $query_builder = array('$or'=>array());

    foreach ($keys_to_search as $value){
        array_push(
            $query_builder['$or'],
            array('metadatas.values.' . $value['key'] => $regex)
        );
    }

    $this->log($query_builder);

    $search_metadata_name = $this->db->filesfolders->find(
        $query_builder, array('sql_fileid' => true)
    );

Upvotes: 1

Related Questions