Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine MongoDB find by id

I'm using odm mongo doctrine and I have to document-classes

class Thing
{
/**
 * @MongoDB\Id
 */
protected $id;

 /**
  * @MongoDB\ReferenceOne(targetDocument="Bundle1:Other")
  */
protected $other;
}

and

class Other
{
/**
 * @MongoDB\Id
 */
protected $id;
}

so in the database a thing looks like :

{
  "_id":ObjectId("43z758634875adf"),
  "other":ObjectId("38z287348d8se")
}

How can I now query for things where other is a given id ?

    $dm=$this->mongo->getManager();
            $answers=$dm
                ->createQueryBuilder('Bundle1:Thing')
                ->field('other')->equals("ObjectId(516c0061975a299edc44b419)")  // <-- ?
                ->getQuery()
                ->execute()->count();       

This produces a wrong mongo query

MongoDB query: {"find":true,"query":{"other":"ObjectId(516c0061975a299edc44b419)"},"fields":[],"db":"maself","collection":"thing"} [] []

When I use

->field('other')->equals("516c0061975a299edc44b419")

the query is also wrong

MongoDB query: {"find":true,"query":{"other":"516c0061975a299edc44b419"},"fields":[],"db":"maself","collection":"thing"} [] []

So how can I search for thing where other id equals an objectId ?

like image 204
john Smith Avatar asked Nov 27 '25 18:11

john Smith


1 Answers

Try

->field('other')->equals(new \MongoId("516c0061975a299edc44b419"))

ObjectId is the internal type for Mongo, represented by \MongoId() in PHP

( But i have also answered in the first topic )

like image 68
Fabien MEYNARD Avatar answered Nov 30 '25 10:11

Fabien MEYNARD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!