简体   繁体   English

MapReduce 与 MongoDB

[英]MapReduce with MongoDB

I have a document like this on MongoDB:我在 MongoDB 上有一个这样的文档:

[
    {
        "option": "My fav food is pizza",
        "person": {
            "id": 1,
            "name": "John"
        },
        "location": {
            "country": "UK",
            "europe": "N"
        }
    },
    {
        "option": "I love football",
        "person": {
            "id": 2,
            "name": "Jack"
        },
        "location": {
            "country": "UK",
            "europe": "N"
        }
    }
]

And I have to obtain something like this, using MapReduce:我必须使用 MapReduce 获得这样的东西:

{
    "country": "UK",
    "value": {
        "count": 2,
        "sentences": [
            "I love football",
            "My fav food is pizza"
        ],
        "people": [
            "Jack",
            "John"
        ]
    }
}

The problem is that I have to deal with it using MapReduce (map, reduce and finalize) on Javascript and I am a little bit stuck on it.问题是我必须在 Javascript 上使用 MapReduce(map、reduce 和 finalize)来处理它,我有点坚持它。

I can't find any good examples as hard as this...我找不到任何像这样难的好例子......

I would appreciate any help :)我将不胜感激任何帮助 :)

we can write a reducer here to create a new object from the array.我们可以在这里写一个reducer来从数组中创建一个新对象。

The below code is an illustration of such an implementation下面的代码是这种实现的说明

 const dataEntity = [ { "option": "My fav food is pizza", "person": { "id": 1, "name": "John" }, "location": { "country": "UK", "europe": "N" } }, { "option": "I love football", "person": { "id": 2, "name": "Jack" }, "location": { "country": "UK", "europe": "N" } } ]; let items = 0; let sentences = []; let people = []; const transformedObject = dataEntity.reduce((acc, curr)=>{ debugger; items+=1; sentences.push(curr.option); people.push(curr.person.name); acc["country"]=curr.location.country; if(!acc["value"]){ acc["value"]={}; } acc["value"]["count"] = items; acc["value"]["sentences"]=sentences; acc["value"]["people"]=people; return acc; },{}) console.log(transformedObject);

This is a simple illustration.这是一个简单的说明。 You can further modify this snippet to fit the requirements.您可以进一步修改此代码段以满足要求。

Cheers.干杯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM