You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Doctrine MongoDB ODM查询构建器查询数组嵌套文档

Got it, let's break this down. You've got that inventory collection with nested instock arrays, and you want to translate common MongoDB Shell queries into Doctrine MongoDB ODM's query builder. I'll walk through some typical use cases based on your sample data so you can see how the mapping works.

1. Fetch all documents in the inventory collection

MongoDB Shell Query

db.inventory.find({})

Doctrine MongoDB ODM Query Builder

use Doctrine\ODM\MongoDB\DocumentManager;

/** @var DocumentManager $dm */
$qb = $dm->createQueryBuilder(\Your\Document\Inventory::class);
$results = $qb->getQuery()->execute();

(Note: Replace \Your\Document\Inventory::class with the actual namespace of your Doctrine document class mapped to the inventory collection.)

2. Find documents where item equals a specific value (e.g., "journal")

MongoDB Shell Query

db.inventory.find({ item: "journal" })

Doctrine MongoDB ODM Query Builder

$qb = $dm->createQueryBuilder(\Your\Document\Inventory::class)
    ->field('item')->equals('journal');

$journalDocs = $qb->getQuery()->execute();

3. Find documents where instock array has an entry with warehouse = "A" and qty >= 5

MongoDB Shell Query

db.inventory.find({ "instock": { $elemMatch: { warehouse: "A", qty: { $gte: 5 } } } })

Doctrine MongoDB ODM Query Builder

$qb = $dm->createQueryBuilder(\Your\Document\Inventory::class)
    ->field('instock')->elemMatch(
        $qb->expr()
            ->field('warehouse')->equals('A')
            ->field('qty')->gte(5)
    );

$matchingDocs = $qb->getQuery()->execute();

4. Find documents where any instock.qty is greater than 10

MongoDB Shell Query

db.inventory.find({ "instock.qty": { $gt: 10 } })

Doctrine MongoDB ODM Query Builder

$qb = $dm->createQueryBuilder(\Your\Document\Inventory::class)
    ->field('instock.qty')->gt(10);

$highQtyDocs = $qb->getQuery()->execute();

5. Update a document: Increase qty for warehouse "C" in the "postcard" item

MongoDB Shell Query

db.inventory.updateOne(
    { item: "postcard", "instock.warehouse": "C" },
    { $inc: { "instock.$.qty": 10 } }
)

Doctrine MongoDB ODM Query Builder

$qb = $dm->createQueryBuilder(\Your\Document\Inventory::class)
    ->update()
    ->field('item')->equals('postcard')
    ->field('instock.warehouse')->equals('C')
    ->field('instock.$.qty')->inc(10)
    ->getQuery()
    ->execute();

If you need to build more complex queries, you can chain expressions, use and()/or() clauses, and leverage all standard MongoDB operators through the query builder's methods.

内容的提问来源于stack exchange,提问作者louffi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:40:08