Félix Veysseyre
Félix Veysseyre

Reputation: 259

Get id of the MongoDB document created in a Symfony3 repository

In my Symfony3 project, I do have some documents such as User, described below:

UserBundle\Document\User:
    repositoryClass: UserBundle\Repository\UserRepository
    fields:
        userId:
            id: true
        email:
            type: string
        firstName:
            type: string
        lastName:
            type: string

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

public function insert($email, $firstName, $lastName)
{
    $data = array('email' => $email,
        'firstName' => $firstName,
        'lastName' => $lastName,
    );

    /* Create query */

    $query = $this->createQueryBuilder();

    /* Add Data */

    $query
        ->insert()
        ->setNewObj($data);

    /* Return */

    $query
        ->getQuery()
        ->execute();

    return true;
}

Rather than returning true, I would like to return the Id of the document I have just created.

Looking for answers, I found this piece of code:

$this->getDocumentManager()->getConnection()->lastInsertId

Unfortunately, it is not returning what I am looking for:

object(MongoDB)[307]
  public 'w' => int 1
  public 'wtimeout' => int 10000

Thanks for your help !

EDIT:

Here is an updated code with the suggestion made in the accepted answer:

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

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

    /* Create query */

    $query = $this->createQueryBuilder();

    /* Add Data */

    $query
        ->insert()
        ->setNewObj($data);

    /* Return */

    $query
        ->getQuery()
        ->execute();

    return $id->__toString();
}

Upvotes: 0

Views: 863

Answers (2)

alcaeus
alcaeus

Reputation: 202

The MongoDB driver writes the ID into the array that is being passed in, but you're not seeing it due to the structure of the query objects. You can get it from the query object that is returned by getQuery():

$query = $queryBuider->getQuery();
$query->execute();

$id = $query->getQuery['newObj']['_id'];

Note however, that this won't necessarily work in future versions, since the new MongoDB driver (which will be used starting with ODM 2.0) doesn't have this functionality.

Upvotes: 0

malarzm
malarzm

Reputation: 2966

The easiest way to solve your problem is to generate the identifier upfront by calling new \MongoId(), adding it to data you're inserting (under _id key) and return known value. Also this is exactly what underlying MongoDB driver does behind the scenes when you're inserting a document without identifier set explicitly (see this doc example)

Upvotes: 1

Related Questions