【发布时间】: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