简体   繁体   中英

How to update embedded document in MongoDB with Doctrine ODM

I'm unable to find how to update embedded documents with Doctrine Mongo ODM in Symfony2. I have a class called Page with many embedded documents "Comments" and I want to use createQueryBuilder to update specific comment. Here is a simple class that I have:

class Page {

protected $id;

/** @MongoDB\EmbedMany */
private $pageComment = array();

}

I searched the whole internet, but I don't see to find any info on how to update subdocuments of a document with Doctrine ODM query builder. I will be thankful for any information as I'm new to both Doctrine and Mongo. In simple words I want to update specific comment in a page after searching for it by id.

Thanks in advance for your help!

If you wan to use queryBuilder use this

$dm->createQueryBuilder('Page')
    ->update()
    ->field('page.pageComment')->set( <$newupdatePageCommentObj> )
    ->field('id')->equals('<matchedId>')
    ->getQuery()
    ->execute();

Or When you generate setters and getters for a EmbedMany member variable it will generate add and remove member functions inside your class. so in your case these will be member functions:

public function addPageComment(type_hint_with_your_pageComment_document $pageComment )
{
    $this->pageComment[] = $pageComment;
}
public function removePageComment( type_hint_with_your_pageComment_document $pageComment )
{
    $this->items->removeElement( $pageComment );
}

So you can use addPageComment() function which will add it if does not exists and will update it will its already there.

You can update only one field at time (instead of pageComment.$ ):

$this->createQueryBuilder('page')
    ->update()
    ->field('id')->equals($pageId)
    ->field('pageComment.id')->equals($pageCommentId)
    ->field("pageComment.$.field1")->set($field1)
    ->getQuery()
    ->execute();
 $yourArrayPageComment = array(
  "id" => new \MongoId($pageCommentId),
  "field1" => $field1,
  ...
)

 $this->createQueryBuilder('page')
            ->update()
            ->field('id')->equals($pageId)
            ->field('pageComment.id')->equals($pageCommentId)
            ->field("pageComment.$")->set($yourArrayPageComment)
            ->getQuery()
            ->execute();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM