mongodb在php中合并文档

时间:2014-02-10 13:12:15

标签: php mongodb

我想将mongodb中的文件与map reduce合并。 如果在其他文档中找到相同名称键,它将以排序顺序合并,则数组中存在键“name”。

示例 - 输入Mongo dB文档有4行

$data[0]['name'] = "mango";
$data[0]['price'][0]['premium'] = 10;
$data[0]['price'][1]['standard'] = 20;

$data[1]['name'] = "apple";
$data[1]['price'][0]['deluxe'] = 500;
$data[1]['price'][1]['good'] = 700;

$data[2]['name'] = "mango";
$data[2]['price'][0]['good'] = 300;

$data[3]['name'] = "apple";
$data[3]['price'][0]['premium'] = 100;
$data[3]['price'][1]['standard'] = 200;

合并后的输出将是两行

$data[0]['name'] = "mango";
$data[0]['price'][0]['premium'] = 10;
$data[0]['price'][1]['standard'] = 20;
$data[0]['price'][2]['good'] = 300;

$data[1]['name'] = "apple";
$data[1]['price'][0]['premium'] = 100;
$data[1]['price'][1]['standard'] = 200;
$data[1]['price'][2]['deluxe'] = 500;
$data[1]['price'][3]['good'] = 700;

这可以用mongodb吗?

1 个答案:

答案 0 :(得分:1)

使用聚合框架非常简单:

db.test.aggregate([{$unwind: '$price'}, {$group: {_id: '$name', price: {$push: '$price'}}}])