如何在Laravel MongoDB中提取子文档

时间:2019-02-01 13:01:58

标签: php mongodb laravel jenssegers-mongodb

你好,开发人员,

我正在使用jenssegers/laravel-mongodb包从Laravel查询我的MongoDB。

我的查询在这里是小提琴:https://mongoplayground.net/p/qzbNN8Siy-3

我有以下JSON

[{
    "id": "GLOBAL_EDUCATION",
    "general_name": "GLOBAL_EDUCATION",
    "display_name": "GLOBAL_EDUCATION",
    "profile_section_id": 0,
    "translated": [
      {
        "con_lang": "US-EN",
        "country_code": "US",
        "language_code": "EN",
        "text": "What is the highest level of education you have completed?",
        "hint": null
      },
      {
        "con_lang": "US-ES",
        "country_code": "US",
        "language_code": "ES",
        "text": "\u00bfCu\u00e1l es su nivel de educaci\u00f3n?",
        "hint": null
      }...
    {
     ....
    }
]

我正在尝试运行以下命令

db.collection.find({ 'id': "GLOBAL_EDUCATION" },{_id:0, id:1, general_name:1, translated:{ $elemMatch: {con_lang: "US-EN"} }})

期望这样的结果

[
  {
    "general_name": "GLOBAL_EDUCATION",
    "id": "GLOBAL_EDUCATION",
    "translated": [
      {
        "con_lang": "US-EN",
        "country_code": "US",
        "hint": null,
        "language_code": "EN",
        "text": "What is the highest level of education you have completed?"
      }
    ]
  }
]

在MoDB中直接查询时,一切都很好,但是当我在Laravel中尝试时,出现了问题。 我已经尝试过MongoDB包中所有可能的已知功能。但无法做到这一点。 这是我的数组

$findArray = [
        [
            'id' => "GLOBAL_EDUCATION",
        ],
        [
            '_id' => 0,
            'id' => 1,
            'general_name' => 1,
            'translated' => [
                '$elemMatch' => ['con_lang' => "US-EN"]
            ],
        ]
];

$model = GlobalQuestions::raw()->find($findArray) //OR
$data = GlobalQuestions::raw(function($collection) use ($findArray){
        return $collection->find($findArray);
});

我在这里做错什么,这种Find()在这里不可能吗,而我必须通过聚合来做到这一点?

1 个答案:

答案 0 :(得分:1)

由于没有人回答这个问题,如果有人遇到相同的问题,我将发布解决方案。 同时进行更多的研发工作,我可以使用whereProject来使用Aggregation Pipelinesspecial method lookups

-----使用Where()和Project()------

$projectArray = [
    '_id' => 0,
    'id' => 1,
    'general_name' => 1,
    'translated' => [
        '$elemMatch' => ['con_lang' => "FR-FR"]
    ],
];

$data = GlobalQuestions::where('id', '=', 'GLOBAL_EDUCATION')
    ->project($projectArray)
    ->get();

---使用聚合和$ unwind ---

$data = GlobalQuestions::raw(function($collection) {
    return $collection->aggregate([
        [
            '$match' => [
                'id' => "GLOBAL_EDUCATION"
            ]
        ],
        [
            '$unwind' => '$translated',
        ],
        [
            '$match' => [
                'translated.con_lang' => "US-EN"
            ]
        ],
        [
            '$project' => [
                '_id'=> 0,
                'id'=> 1,
                'general_name' => 1,
                'translated' => 1,
            ]
        ]
    ]);
})->first();