How to remove multiple documents in Doctrine MongoDB ODM
Asked Answered
B

1

7

How can I remove multiple documents in doctrine mongodb odm? In PHP class I should be able to do it using the following code:

 $db->collection->remove(array("age" => 18));

How can I do it in doctrine mongo odm?

Basile answered 2/7, 2012 at 20:1 Comment(0)
S
17

You have two options. Using the DocumentManager, you can request the collection for a given class. This will actually return a Doctrine\MongoDB\Collection instance, which wraps the base MongoCollection to support logging and events. The underlying MongoCollection is available if you really want it, too:

$collection = $dm->getDocumentCollection('Documents\User');
$collection->remove(array('age' => 18));

// Use the raw MongoCollection to bypass logging and events
$mongoCollection = $collection->getMongoCollection();
$mongoCollection->remove(array('age' => 18));

Alternatively, you can use the query builder API:

$qb = $dm->createQueryBuilder('Documents\User');
$qb->remove()
    ->field('age')->equals(18)
    ->getQuery()
    ->execute();

If you stop at getQuery(), you can use the debug() method on the returned query object to see what Doctrine will execute against the database.

Ster answered 2/7, 2012 at 23:48 Comment(1)
I haven't found the first option in the documentation, It has small code as I wanted. Thank you!Basile

© 2022 - 2024 — McMap. All rights reserved.