Symfony 5 php mongo odm array field

Symfony 5 php mongo odm array field

By d-erf | Devtips | 10 Oct 2020


Hello,

 

I've been searching this information for a couple of hour, and as it's now well documented, i publish solution to prevent other people losing to much time for same need.

 

Mongodb odm in a symfony 5 project.

 

How to annotate type in Document class for allowing array to be correctly interpreted and correctly converted to json in the mongo database?

 

https://www.doctrine-project.org/projects/doctrine-mongodb-odm/en/2.1/reference/basic-mapping.html

 

We see as basic mapping types:

 

01301400f6169e04cac2b04d96210e2ca1ba3c46c35cc736e08f4154e5c8fa3c.png

I've arrays to set with odm, to be converted in json.

 

Tried string, json_encoded string, raw... Nothing were ok, always converted to a string in mongo, so impossible to find on the array values in mongo: useless.

 

From the document site, nothing else about arrays, only customs types.

 

After a couple of hour of searching and trying, there 2 other types useful in that purpose: collection and hash types:

 

    /**
     * @MongoDB\Field(type="hash")
     */
    protected $vmdata;

    public function getVmdata() {

        return $this->vmdata;

    }

    public function setVmdata($vmdata) {

        $this->vmdata      = $vmdata;

        return;

    }

 

Now, when i set:

        $template->setVmdata($vmdata);

 

$vmdata being a php associative array, now it's correctly converted to a good json content rightly inserted in mongo.

 

 

Hope it helps friends, see you!

 

Have you read my other posts, click here!

 

Don't you know publish0x? It's an alternative and innovative free blogging platform paying in crypto just for viewing (with their bat coins pool) and for authoring, clic here to try

 

Follow me on publish0x, and on twitter!

 

See you all!

 

 

How do you rate this article?

6



Devtips
Devtips

Dev tips and tricks

Publish0x

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.