dpoppu4300 2016-08-02 11:30
浏览 2617

如何在MongoDB中使用$ in查询中的ObjectId?

I have the following query in MongoDB

$this->createQueryBuilder()
            ->field('actor')->in($actorIdArray)
            ->getQuery()
            ->execute();

where the field actor is an object reference with annotation

@MongoDB\ReferenceOne(targetDocument="User", simple=true)

which means it will store the object Id instead of the full reference.

When $actorIdArray is an array of id with the form

["5706cb39821b166d3931f34f", "56015f7d4f8bd90b769e6e75"]

the query does not return nothing, which is the expected since the filed actor contains object id.

However, if I build the array this way

[new MongoId("5706cb39821b166d3931f34f"), new MongoId("56015f7d4f8bd90b769e6e75")]

it doesn't work either, which is quite surprising for me.

The log shows the query is made

{ "actor": {"$in":[{"$id":"5706cb39821b166d3931f34f"},{"$id":"56015f7d4f8bd90b769e6e75"}]}}

and I think it should be something like this

{ "actor": {"$in":[ObjectId("5706cb39821b166d3931f34f"),ObjectId("56015f7d4f8bd90b769e6e75"]}}

Not sure if I am doing something wrong, any ideas?

  • 写回答

1条回答 默认 最新

  • dsfds4551 2016-08-02 13:52
    关注

    Doctrine wants your array to be an array of documents.

    You can load document references without query.

    $dm = $this->get('doctrine.odm.mongodb.document_manager'):
    
    $documents = array();
    foreach($actorIdArray as $id){
        $documents[] = $dm->getReference('AppBundle:Actor',$id); // <- this is the key
    }
    
    $this->createQueryBuilder()
                ->field('actor')->in($documents)
                ->getQuery()
                ->execute();
    
    评论

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作