Ahmed-F
Ahmed-F

Reputation: 147

Mongodb & Symfony QueryBuilder

Does someone know where I can find some informations about Mongodb QueryBuilder in Symfony2 please? Maybe some examples or some tutorials. I googled the question but didn't find something good enough.. More specifically I want to retrieve a field in a document based on the embedded document. Here is an example of document :

{
"name":"Foo",
"age":"25",
"gender":"Male",
"products":[
        {
            "name":"Apple",
            "price":"12.00",
            "date":"2015-12-02"
        },
        {
            "name":"Banana",
            "price":"9.00",
            "date":"201-11-31"
        },
]

}

And I want to retrieve the name "Foo" based on the date in products array. At the moment I use distinct() to list all fields in products.

Upvotes: 1

Views: 2336

Answers (1)

BentCoder
BentCoder

Reputation: 12740

Simple doctrine mongodb example for EmbedMany in symfony

Assume that a League may have one or many Teams so it is a Embed Many like in your case. Full example is above. If you want more info then I think first 5 posts are enough for you.

EXAMPLE USAGE

->findOneByProperty('name', 'Premiership')

REPO

use Doctrine\ODM\MongoDB\DocumentRepository;

class LeagueRepository extends DocumentRepository
{
    /**
     * @param string $field
     * @param string $data
     *
     * @return array|null|object
     */
    public function findOneByProperty($field, $data)
    {
        return
            $this->createQueryBuilder('League')
                ->field($field)->equals($data)
                ->getQuery()
                ->getSingleResult();
    }
}

DUMMY DATA

db.getCollection('league').find({})
/* 1 */
{
    "_id" : ObjectId("564fa07add576ebcf90041ac"),
    "name" : "Super Lig",
    "createdAt" : ISODate("2015-11-20T22:36:42.000Z")
}

/* 2 */
{
    "_id" : ObjectId("564fa081dd576ebbf90041ad"),
    "name" : "Premiership",
    "createdAt" : ISODate("2015-11-20T22:36:49.000Z"),
    "updatedAt" : ISODate("2015-11-20T22:37:33.000Z"),
    "teams" : [ 
        {
            "_id" : ObjectId("564fa0a6dd576ef2f80041ad"),
            "name" : "Arsenal",
            "createdAt" : ISODate("2015-11-20T22:37:26.000Z")
        }, 
        {
            "_id" : ObjectId("564fa0addd576ebaf90041ad"),
            "name" : "Liverpool",
            "createdAt" : ISODate("2015-11-20T22:37:33.000Z")
        }
    ]
}

Upvotes: 1

Related Questions