使用“集合”合并与查询匹配的所有子文档的列表? [英] Using "aggregate" to combine a list of all subdocuments that match query?
问题描述
我正在尝试使用PHP mongo库在这样的数据结构上聚合:
I'm trying to use a PHP mongo library to "aggregate" on a data structure like this:
{
"_id": 100,
"name": "Joe",
"pets":[
{
"name": "Kill me",
"animal": "Frog"
},
{
"name": "Petrov",
"animal": "Cat"
},
{
"name": "Joe",
"animal": "Frog"
}
]
},
{
"_id": 101,
"name": "Jane",
"pets":[
{
"name": "James",
"animal": "Hedgehog"
},
{
"name": "Franklin",
"animal": "Frog"
}
}
例如,如果我想获取所有动物为青蛙的子文档。请注意,我不希望所有匹配的超级文档(即带有_id的文档)。我想得到一个看起来像这样的数组:
For example, if I want to get all subdocuments where the animal is a frog. Note that I do NOT want all matching "super-documents" (i.e. the ones with _id). I want to get an ARRAY that looks like this:
[
{
"name": "Kill me",
"animal": "Frog"
},
{
"name": "Joe",
"animal": "Frog"
},
{
"name": "Franklin",
"animal": "Frog"
}
]
我应该使用哪种语法(在PHP中)完成此任务?我知道它与聚合有关,但找不到与该特定方案匹配的任何东西。
What syntax am I supposed to use (in PHP) to accomplish this? I know it has to do with aggregate, but I couldn't find anything that matches this specific scenario.
推荐答案
您可以使用低于汇总。 $ match
查找数组值为 Frog
和 $ unwind $的文档c $ c>
pets
数组。 $ match
,其中文档具有 Frog
,最后一步是 group
将匹配的文档放入数组。
You can use below aggregation. $match
to find documents where array has a value of Frog
and $unwind
the pets
array. $match
where document has Frog
and final step is to group
the matching documents into array.
<?php
$mongo = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$pipeline =
[
[
'$match' =>
[
'pets.animal' => 'Frog',
],
],
[
'$unwind' =>'$pets',
],
[
'$match' =>
[
'pets.animal' => 'Frog',
],
],
[
'$group' =>
[
'_id' => null,
'animals' => ['$push' => '$pets'],
],
],
];
$command = new \MongoDB\Driver\Command([
'aggregate' => 'insert_collection_name',
'pipeline' => $pipeline
]);
$cursor = $mongo->executeCommand('insert_db_name', $command);
foreach($cursor as $key => $document) {
//do something
}
?>
这篇关于使用“集合”合并与查询匹配的所有子文档的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!