如何提取 laravel mongodb 中的子文档

How do I extract subdocument in laravel mongodb

你好开发者,

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

这是我的查询 Fiddle: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() 在这里是不可能的,我必须通过聚合来做到这一点吗?

由于没有人回答这个问题,如果有人遇到同样的问题,我会发布解决方案。 在相同的基础上进行更多的研发,我能够使用 where and Project as well by Aggregation Pipelines.

做到这一点

----- 使用 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();