Pregunta

I would like to use MongoDB to store the logs of my json api. I am using the Doctrine 2 ODM.

Reading through the manual I understand that to store my json api response, I should use the @Field annotation with some well chosen data type. However, I do not find the one that would fit the BSON data type.

Is there any data type that will allow me to get things working with something like

$myRecord->setResponse($json_response);

and later on perform MongoDB queries like

db.Logs.find({"response.user": "foo"});

? What is the correct way to deal with this ?

¿Fue útil?

Solución

After a few tries, here I am: the correct type to do this is the Hash type. Our document has a response field that looks like this:

/**
 * @MongoDB\Hash
 */
 protected $response;

And the call to set the value is as follow:

$myRecord->setResponse(json_decode($result, true));

This is it!

Edit: As I had some issues to retrieve the stored values, I came to use mongodb callbacks :/

/**
 * (...)
 * @MongoDB\HasLifecycleCallbacks 
 */
class Log
{
    (...)
    /** @MongoDB\PreLoad */
    public function preLoad(array &$data)
    {
        $data["response"] = json_encode($data["response"]);
    }

    /** @MongoDB\PrePersist */
    public function prePersist()
    {
        $a_json = json_decode($this->getResponse(), true);
        $this->setResponse($a_json);
    }

Which makes the set call straight, by the way:

$myRecord->setResponse($result);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top