fef fef - 13 days ago 6
PHP Question

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();
}

Answer

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)

Comments