MongoDB查找符合条件的嵌套对象

编程入门 行业动态 更新时间:2024-10-22 09:35:55
本文介绍了MongoDB查找符合条件的嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个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查找符合条件的嵌套对象

本文发布于:2023-11-22 20:42:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618947.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   符合条件   对象   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!