【问题标题】:Find results and Aggregate results differ, despite same query尽管查询相同,但查找结果和汇总结果不同
【发布时间】:2014-07-09 14:38:50
【问题描述】:

我正在尝试在结构如下的文档中搜索人员。在我的“查找”功能中,我会得到 10 个结果。但是,我的聚合返回少于那个(大约 7,但似乎取决于数据)。我尝试循环遍历 test_find 的结果,并根据 test_find 结果的 ID 添加“$and”规定,但在某些情况下,即使在 find() 中使用相同的查询,它也不会返回任何找到的结果陈述。

JSON 对象结构:

{
    id: "53b563c372f4f85b787b23c8",
    n: "Organization Name"
    fn: "filename.csv"
    p: [ // array of people
        {
            given_name: "John",
            surname: "Smith",
            sc: { // there is actually more data, but only the .sc. data is relevant to search
                g: "John",
                s: "Smith"
            }
        }
    ]
}

当前代码:

/***** $search_column_query dump ********/
{
    '$and': {
        { "p.sc.s": "Smith" },
        { "p.sc.g": "John" }
    }
}
/**************************************/

$test_find = $db->genealogical_data->find($search_column_query)->limit(10);

// This gets 10 results of documents matching the search query
foreach ($test_find as $result) { 
    var_dump($result["n"]); // "n" is the name
}



// This gets less than 10 (7 in the case of John Smith) results of documents matching the search query
$aggregation = array(
        array( '$match' => $search_column_query ), 
        array( '$limit' => 10 ),
        array( '$unwind' => '$p' ),
        array( '$match' => $search_column_query),
        array( '$group' => array(
            '_id' => '$n',
            'filename' => array( '$first' => '$fn' ),
            'people' => array( '$push' => '$p' )
        )),
        array( '$sort' => array('_id' => 1) ),
    );
$documents_with_results = $db->genealogical_data->aggregate($aggregation);

似乎我的搜索查询根本上是错误的,或者在聚合中使用不正确。非常感谢任何帮助。

【问题讨论】:

  • 如果您的示例使用实际的 JSON 和 MongoDB shell 而不是 PHP,大多数人会更容易帮助您。
  • @JohnnyHK 我将对象/文档转换为 JSON。不过,我对在 shell 中做 MongoDB 工作不是很熟悉,所以我留下了我的 PHP 代码以避免出现问题。
  • 您能否提供一个通过正常查询而不是通过聚合找到的文档之一的示例?
  • 顺便说一下,$and 是不必要的。当您将多个 field:value 对放入查询中时,它们都必须得到满足。但我怀疑这是你问题的原因。
  • 第一个 JSON 对象就是一个例子。

标签: mongodb mongodb-query aggregation-framework mongodb-php


【解决方案1】:

您在 find 中使用了不正确的查询。
您应该使用$elemMatch operator 来确保您的两个条件匹配到相同的子文档/元素。

{ "p": { "$elemMatch": {“sc.s”:“史密斯”,“sc.g”:“约翰”} } }

因为您 $unwind 首先在聚合中,所以您的查询最终是正确的,因为它会自动应用于数组的单个元素。

【讨论】:

  • 当您使用另一种格式(分别匹配 s 和 g)时会发生什么情况,即使有同一元素中没有“john smith”。
  • 所以在我的聚合的第一个 $match 中,我应该使用 $elemMatch 而不是我现在正在做的事情? “查找”更多是为了测试目的,因为我返回的数据是错误的。
  • 从技术上讲,是的,但这并不重要,因为它现在所做的只是通过 $unwind 一些文档,这些文档最终将在第二次匹配时被完全删除(因为它们不会在任何数组元素中都有“john smith”)。
  • 问题是当我在第一场比赛后将其限制为10个时,将需要10个,其​​中3个将由于您提到的问题而出现故障。所以如果我会尝试切换第一场比赛,看看是否能解决它。
  • 啊,对不起,我想我看错了你的文件。我刚刚编辑了我的答案 - 我误读了文档,在您的情况下,您需要在数组字段“p”之后立即使用 $elemMatch。
猜你喜欢
  • 2021-12-08
  • 2016-11-18
  • 2017-04-28
  • 1970-01-01
  • 2021-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-27
相关资源
最近更新 更多