Reputation: 277
I've the following documents in my collection:
{
"attr_a" : {
"_id" : ObjectId("51877b939a9cd88730d6030e"),
"key" : "a-key-1",
"name" : "a name 1"
},
"attr_b" : {
"_id" : ObjectId("51877b9392lfd88730d602sw"),
"key" : "b-key-1",
"name" : "b name 2"
}
}
{
"attr_a" : {
"_id" : ObjectId("51877b939a9cd88730d6030e"),
"key" : "a-key-2",
"name" : "a name 2"
},
"attr_b" : {
"_id" : ObjectId("51877b9392lfd88730d602sw"),
"key" : "b-key-2",
"name" : "b name 2"
}
}
And I want to create a query the produces as result something like:
{
"attr_a" : [{
"_id" : ObjectId("51877b939a9cd88730d6030e"),
"key" : "a-key-1",
"name" : "a name 1"
},
{
"_id" : ObjectId("51877b939a9cd88730d6030e"),
"key" : "a-key-2",
"name" : "a name 2"
}
],
"attr_b" : [{
"_id" : ObjectId("51877b9392lfd88730d602sw"),
"key" : "b-key-1",
"name" : "b name 2"
},
{
"_id" : ObjectId("51877b9392lfd88730d602sw"),
"key" : "b-key-2",
"name" : "b name 2"
}]
}
I'm using MongoDB 2.6.x and Spring Data 1.6.5 and I'm trying to figure out if it can be done with the aggregation framework or with the map-reduce (in both case it should be done in real time) or in another different way.
Or should I take in consideration to introduce a Solr/Elastic Search?
Any suggestion?
Thanks in advance, Alexio Cassani
Upvotes: 0
Views: 144
Reputation: 311865
You can do that by grouping the entire collection into a single doc, using $push
to assemble the arrays:
db.test.aggregate([{$group: {
_id: null,
attr_a: {$push: '$attr_a'},
attr_b: {$push: '$attr_b'}
}}])
Upvotes: 1