mongodb-odm icon indicating copy to clipboard operation
mongodb-odm copied to clipboard

Create "notReferences" query ?

Open lucalbert opened this issue 6 years ago • 3 comments

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?

lucalbert avatar Apr 03 '18 09:04 lucalbert

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.

malarzm avatar Apr 03 '18 10:04 malarzm

Nice @malarzm!

Thanks you.

lucalbert avatar Apr 03 '18 10:04 lucalbert

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

jcaillot avatar Mar 21 '20 05:03 jcaillot