Get id of the MongoDB document created in a Symfony3 repository
<p>In my <strong>Symfony3</strong> project, I do have some documents such as <strong>User</strong>, described below:</p>

<pre><code>UserBundle\Document\User:
    repositoryClass: UserBundle\Repository\UserRepository
    fields:
        userId:
            id: true
        email:
            type: string
        firstName:
            type: string
        lastName:
            type: string
</code></pre>

<p>Some time, I want to create a user document through the user repository.
Working around the <em>createQueryBuilder()</em>, I have built this method:</p>

<pre><code>public function insert($email, $firstName, $lastName)
{
    $data = array('email' =&gt; $email,
        'firstName' =&gt; $firstName,
        'lastName' =&gt; $lastName,
    );

    /* Create query */

    $query = $this-&gt;createQueryBuilder();

    /* Add Data */

    $query
        -&gt;insert()
        -&gt;setNewObj($data);

    /* Return */

    $query
        -&gt;getQuery()
        -&gt;execute();

    return true;
}
</code></pre>

<p>Rather than returning <code>true</code>, I would like to <strong>return the Id of the document I have just created</strong>.</p>

<p>Looking for answers, I found this piece of code:</p>

<pre><code>$this-&gt;getDocumentManager()-&gt;getConnection()-&gt;lastInsertId
</code></pre>

<p>Unfortunately, it is not returning what I am looking for:</p>

<pre><code>object(MongoDB)[307]
  public 'w' =&gt; int 1
  public 'wtimeout' =&gt; int 10000
</code></pre>

<p>Thanks for your help !</p>

<p>EDIT:</p>

<p>Here is an updated code with the suggestion made in the accepted answer:</p>

<pre><code>public function insert($email, $firstName, $lastName)
{
    $id = new MongoId();

    $data = array(
        '_id' =&gt; $id,
        'email' =&gt; $email,
        'firstName' =&gt; $firstName,
        'lastName' =&gt; $lastName,
    );

    /* Create query */

    $query = $this-&gt;createQueryBuilder();

    /* Add Data */

    $query
        -&gt;insert()
        -&gt;setNewObj($data);

    /* Return */

    $query
        -&gt;getQuery()
        -&gt;execute();

    return $id-&gt;__toString();
}
</code></pre>