Reputation: 298
I want to merge documents in mongodb with map reduce. There is key "name" is in array if same name key found in other documents it will merge in sorted order.
Example - Input Mongo dB documents have 4 rows
$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;
Output after merge it will be two row
$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;
Is this possible with mongodb?
Upvotes: 0
Views: 148
Reputation: 832
It's very simple to do with Aggregation Framework like this:
db.test.aggregate([{$unwind: '$price'}, {$group: {_id: '$name', price: {$push: '$price'}}}])
Upvotes: 1