简体   繁体   中英

Query for a Document Nested in an Array using Doctrine mongodb odm

I want to execute Document Nested in an Array queries with the Doctrine mongodb odm query builder

I have basically a structure similar to :

db.inventory.insertMany( [

{ item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] },

{ item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] },

{ item: "postcard", instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }

]);

I want to execute this shell query within the query builder

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

I have tried this, but this won't work as it ignores the field 'instock'.

$qb->field('instock')->field('warehouse')->equals('A')->field('qty')->equals(5)

Keep in mind that doing the following

$qb->field('instock.warehouse')->equals('A')->field('instock.qty')->equals(5)

is a different logic ( check second example ), because it matches not necessarily the same embedded document.

I can implement it using $where and a loop, but it is ugly and slow. any better ideas ?

ODM supports embedded documents via query builder so you can do the following:

$qb->field('instock')->equals(new InStock('A', 5));

If using objects is not what you want I think you can do away with associative array instead of new InStock() .

using $elemMatch, this is the way to solve this issue :

$qb->expr()->field('instock')->elemMatch(
        $qb->expr()
            ->field('warehouse')->equals('A')
            ->field('qty')->equals(5)
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM