0

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

4
  • if you have some other dynamic keys then you can use $and in mongodb. check : docs.mongodb.org/manual/reference/operator/query/and Commented Jan 11, 2016 at 17:23
  • @Monty the problem is that i don't know the key names unless i iterate all collections to get all available keys and then build the query but i am worried about performance Commented Jan 11, 2016 at 17:25
  • 1
    In which case you might be better off transferring to a structure where you can query key names Commented Jan 11, 2016 at 18:01
  • @Sammaye that is actually a pretty good idea i think. i was querying all my existing files to collect the key names but now with that the number of elements to iterate is much smaller. definitely trying that Commented Jan 11, 2016 at 18:04

1 Answer 1

1

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)
    );
Sign up to request clarification or add additional context in comments.

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.