如何根据相关文档查询MongoDB集合(在Doctrine中)

时间:2016-12-16 12:21:04

标签: mongodb doctrine-odm nosql

我的Doctrine ODM项目中有一些相关的集合......

# Contract.mongodb.yml
Project\Contract\Domain\Contract:
  type:             document
  repositoryClass:  Project\SymfonyBundle\ContractBundle\Repository\ContractRepository
  collection:       Contracts
  fields:
    id:
      type:     id
      id:       true
      strategy: UUID
    slug:
      type:   string
      length: 128
      unique: true
      gedmo:
        slug:
          separator:  -
          style:      default
          fields:
            - refNo
            - name
    name:
      type: string
    refNo:
      type:   string
    purpose:
      type: string
    budgetAmount:
      type: int
    budgetCurrency:
      type:   string
      length: 3
    startDate:
      type: date_immutable
    endDate:
      type: date_immutable
    provider:
      type: string
  referenceOne:
    provider:
      targetDocument: Project\Contract\Domain\Provider
      cascade:
        - persist
        - merge
        - detach
        - refresh
  referenceMany:
    reports:
      targetDocument: Project\Report\Domain\Report
      cascade:
        - all

# Provider.mongodb.yml
Project\Contract\Domain\Provider:
  type:             document
  repositoryClass:  Project\SymfonyBundle\ContractBundle\Repository\ProviderRepository
  collection:       Providers
  fields:
    id:
      type:     id
      id:       true
      strategy: UUID
    slug:
      type:   string
      length: 128
      unique: true
      gedmo:
        slug:
          separator:  -
          style:      default
          fields:
            - name
    name:
      type:   string
      unique: true
  referenceMany:
    users:
      targetDocument: Project\User\Domain\User
      cascade:        []

# User.mongodb.yml
Project\User\Domain\User:
  type:             document
  repositoryClass:  Project\SymfonyBundle\UserBundle\Repository\UserRepository
  collection:       Users
  fields:
    id:
      type:     id
      id:       true
      strategy: UUID

我想要做的是获取给定用户的合同,但我无法确定如何根据用户查询Contracts集合。我需要进行2次查询吗? 1获得用户的提供者&然后第二个查询链接到其中一个提供商的合同?

如果您能够在控制台和Doctrine中建议我如何做到这一点,我会很感激。

预先感谢您的帮助:o)

1 个答案:

答案 0 :(得分:0)

您可以使用汇总管道并使用$lookup运算符加入文档,请参阅 - https://docs.mongodb.com/v3.2/reference/operator/aggregation/lookup/

但是,如果这很常见,我会考虑重新建模您的文档。