问题
I am trying MapReduce program in MongoDB, I have MongoDB collection with following data type:
{ "_id" : ObjectId("57aea85af405910cfcd2bfeb"), "friendList" : [ "Karma", " Tom", " Ram", " Bindu", " Shiva", " Kishna", " Bikash", " Bakshi", " Dinesh" ], "user" : "Hari" }
{ "_id" : ObjectId("57aea85bf405910cfcd2bfec"), "friendList" : [ "Karma", " Sita", " Bakshi", " Hanks", " Shyam", " Bikash" ], "user" : "Howard" }
{ "_id" : ObjectId("57aea85cf405910cfcd2bfed"), "friendList" : [ "Dinesh", " Ram", " Hanks", " Bindu", " Howard", " Bikash", " Shyam", " Bakshi" ], "user" : "Sita" }
{ "_id" : ObjectId("57aea85cf405910cfcd2bfee"), "friendList" : [ "Hanks", " Tom", " Karma", " Hari", " Dinesh" ], "user" : "Shiva" }
{ "_id" : ObjectId("57aea85cf405910cfcd2bfef"), "friendList" : [ "Bakshi", " Kishna", " Hanks", " Shiva", " Bindu", " Hari", " Karma", " Sita" ], "user" : "Dinesh" }
My code :
map = Code("""
function () {
for (var i=0; i<this.friendList.length; i++)
{
var friendValue = this.friendList[i];
var userValue = this.user;
var tempUserValue = userValue.toLowerCase().trim();
var tempFriendValue = friendValue.toLowerCase().trim();
if(tempUserValue>tempFriendValue)
{
var temp = userValue;
userValue = friendValue;
friendValue = temp;
}
Here I have used composite key and now before sending this key-value pairs to the reducer, have sorted key.
For example my output is:
{
"_id" : {
"user" : "Dinesh",
"friend" : " Hari"
},
"value" : {
"friendList" : [
"Karma",
" Tom",
" Ram",
" Bindu",
" Shiva",
" Kishna",
" Bikash",
" Bakshi",
" Dinesh"
]
}
}
And:
{
"_id" : {
"user" : "Dinesh",
"friend" : " Hari"
},
"value" : {
"friendList" : [
"Bakshi",
" Kishna",
" Hanks",
" Shiva",
" Bindu",
" Hari",
" Karma",
" Sita"
]}}
But I want output like:
"_id" : {
"user" : "Dinesh",
"friend" : " Hari"
},
"value" : {
"friendList" : [
"Bakshi",
" Kishna",
" Hanks",
" Shiva",
" Bindu",
" Hari",
" Karma",
" Sita"
]
[
"Karma",
" Tom",
" Ram",
" Bindu",
" Shiva",
" Kishna",
" Bikash",
" Bakshi",
" Dinesh"
]}
I am trying but could not get it. I highly appreciate your help.
来源:https://stackoverflow.com/questions/38949291/group-document-by-their-key-in-monogodb-mapreduce