mongodb-odm
mongodb-odm copied to clipboard
Create "notReferences" query ?
Hello everyone,
In my application, I have a reference (One) between 2 entities:
namespace App\Document
class Offer
{
/**
* @MongoDB\ReferenceOne(targetDocument="Customer")
*/
protected $customer;
}
When I want to retrieve all the references, no problem:
$repository = $container->get('doctrine_mongodb')->getManager()->getRepository(Offer::class);
$offers = $repository->findBy (['customer' => $customer]);
// or
$dm = $container->get('doctrine_mongodb')->getManager();
$qb = $dm->createQueryBuilder(Offer::class);
$offers = $qb
->field('customer')->references($customer)
->getQuery()
;
// or
$offers = $qb
->field('customer')->equals($customer)
->getQuery()
;
In both cases, the query is the same:
db.offers.find({ "customer.$id": ObjectId("5abe0295b4bfd00008089c73") });
Now, I want to get all the documents that do not have the reference ! When i try this :
$dm = $container->get ('doctrine_mongodb')->getManager();
$qb = $dm->createQueryBuilder(Offer::class);
$offers = $qb
->field('customer') ->notEqual($customer)
-> getQuery()
;
I get the following error: "Catchable Fatal Error: Object of class MongoDBODMProxies_CG_\App\Document\Customer could not be converted to string"
If i try this:
$offers = $qb
->field('customer.$id')->notEqual($customer->getId())
->getQuery()
;
I get the following query:
db.offers.find({ "customer.$id": { "$ne": "5abe0295b4bfd00008089c73" } }); // It's not a ObjectId
How to launch such a query?
Given querying by customer.$id
you need to explicitly tell ODM that there's ObjectId
inside, so:
>field('customer.$id')->notEqual(new \MongoId($customer->getId()))
Offhand, given we have references
and includesReferenceTo
helper methods it might be feasible to provide their counterparts. Marking as feature.
Nice @malarzm!
Thanks you.
my 55 cents :
// "$nor performs a logical NOR operation on an array of **ONE** or more query expression"
// https://docs.mongodb.com/manual/reference/operator/query/nor/
$qb->addNor($qb->expr()->field('field_name')->references($document));