获取在Symfony3存储库中创建的MongoDB文档的id


Get id of the MongoDB document created in a Symfony3 repository

在我的Symfony3项目中,我确实有一些文档,如User,如下所述:

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

有时候,我想通过用户存储库创建一个用户文档。围绕createQueryBuilder(),我建立了这个方法:

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

我希望返回我刚刚创建的文档的Id,而不是返回true

为了寻找答案,我发现了这段代码:
$this->getDocumentManager()->getConnection()->lastInsertId

不幸的是,它没有返回我正在寻找的东西:

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

谢谢你的帮助!

编辑:

下面是一个更新的代码,其中包含了被接受的答案中提出的建议:

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

解决问题的最简单方法是通过调用new 'MongoId()来生成标识符,将其添加到您插入的数据(在_id键下)并返回已知值。此外,这正是底层MongoDB驱动程序在幕后做什么,当你插入一个文档没有标识符设置显式(参见这个文档的例子)

MongoDB驱动程序将ID写入正在传入的数组中,但由于查询对象的结构,您无法看到它。您可以从getQuery()返回的查询对象中获取它:

$query = $queryBuider->getQuery();
$query->execute();
$id = $query->getQuery['newObj']['_id'];

但是,请注意,这在未来的版本中不一定有效,因为新的MongoDB驱动程序(将从ODM 2.0开始使用)不具有此功能。