我有一个MongoDB文档,其结构类似于以下结构.我正在根据people.search_columns.surname和people.columns.givenname进行搜索.因此,例如,当我搜索给定的名称"Valentine"时,我想找回该文档,但不应包括Nicholas Barsaloux.
I have a MongoDB document that is structured similar to the structure below follows. I am searching based on people.search_columns.surname and people.columns.givenname. So for example, when I search for the given name of "Valentine", I want to get the document back, but Nicholas Barsaloux should not be included.
数据结构:
[_id] => MongoId Object ( [$id] => 53b1b1ab72f4f852140dbdc9 ) [name] => People From 1921 [people] => Array ( [0] => Array ( [name] => Barada, Valentine [search_columns] => Array ( [surname] => Array ( [0] => Mardan, [1] => Barada ) [givenname] => Array ( [0] => Valentine ) ) ) [1] => Array ( [name] => Barsaloux, Nicholas [search_columns] => Array ( [surname] => Array ( [1] => Barsaloux ) [givenname] => Array ( [0] => Nicholas ) [place] => Array ( ) ) ) )这是我正在处理的代码:
Here is the code I was working on:
$criteria = array("people" => array( '$elemMatch' => array("givenname" => "Valentine") )); $projection = array("people" => true); $documents_with_results = $db->genealogical_data->find($criteria, $projection)->skip(0)->limit(5);当前该代码返回零结果.
Currently that code returns zero results.
推荐答案由于数组是嵌套的,因此无法像find一样使用基本投影.同样,为了从文档中过滤"数组内容,您需要首先展开"数组内容.为此,您可以使用聚合框架:
Since the arrays are nested you cannot use basic projection as you can with find. Also in order to "filter" the array contents from a document you need to "unwind" the array content first. For this you use the aggregation framework:
$results = $db->genealogical_data->aggregate(array( array( '$match' => array( 'people.search_columns.givenname' => 'Valentine' )), array( '$unwind' => '$people' ), array( '$match' => array( 'people.search_columns.givenname' => 'Valentine' )), array( '$group' => array( '_id' => '$id', 'name' => array( '$first' => '$name' ), 'people' => array( '$push' => '$people' ) )) ));第一个 $match 的点阶段是减少可能符合您条件的文档.第二次是在 $unwind ,从结果中过滤"文档中的实际数组"项.
The point of the first $match stage is to reduce the documents that possibly match your criteria. The second time is done after the $unwind, where the actual "array" items in the document are "filtered" from the results.
最终的 $group 将原始数组恢复为正常,减去不符合条件的项目.
The final $group puts the original array back to normal, minus the items that do not match the criteria.
更多推荐
MongoDB查找符合条件的嵌套对象
发布评论