Reputation: 1311
I have documents of the following format:
{
"_id" : ObjectId("58af1ee3f78a9945bd9fc94d"),
"rounds" : {
"matches" : {
"team1" : {
"name" : "Manchester United",
"score1" : 1
},
"team2" : {
"name" : "Tottenham Hotspur",
"score2" : 0
}
}
}}
And I would like to get somenthing like this:
{
"_id" : ObjectId("SomeID"),
"rounds" : {
"matches" : {
"team1" : {
"name" : "Manchester United",
"score1" : 1
}
}
}
}
and
{
"_id" : ObjectId("SomeID"),
"rounds" : {
"matches" : {
"team2" : {
"name" : "Tottenham Hotspur",
"score2" : 0
}
}
}
}
I'm looking for something like unwind but unwind is applied only on arrays. How can I transform matches into an array of JSON? Any other ideas to achieved the desired result are welcome
Upvotes: 0
Views: 1712
Reputation: 234
Maybe a mapreduce function, with just a map function? I don't really know your use case but if you are just returning one document at a time it might be best to do the refactoring after mongo returns the results.
db.somcollection.mapReduce(
function(){
var matcharray = [];
for (var match in this.rounds.matches) {
if (this.rounds.matches.hasOwnProperty(match)) {
matcharray.push({team:match,other:this.rounds.matches[match]});
}
}
emit('matches',matcharray);
},
function(key,values){
return ( values );
},
{
query:{"_id" : ObjectId("58af1ee3f78a9945bd9fc94d")},
out: "somename"
}).find()
This results in the following, which is at least an array but not quite what you wanted using key/value pairs for everything.
{
"_id" : "matches",
"value" : [
{
"team" : "team1",
"other" : {
"name" : "Manchester United",
"score1" : 1
}
},
{
"team" : "team2",
"other" : {
"name" : "Tottenham Hotspur",
"score2" : 0
}
}
]
}
Upvotes: 1