【问题标题】:MongoDB: Mapping without reduce?MongoDB:没有减少的映射?
【发布时间】:2017-08-14 15:49:06
【问题描述】:

我想创建一个地图并查询它。我来自 CouchDB,它允许使用视图。 使用 MongoDB 可以做到这一点,增量 Map/Reduce 是否正确?

示例:获取一些文档并在处理后为每个待办事项发出带有日期的行并查询结果。

文档:

{
   name: "Max",
   todos: [
      {
         title: "Bring milk home.",
         isImportant: true,
         date: 1502557780
      }
   ]
}

示例映射函数:

function() {
   for (var i = 0; i < this.todos.length; i++) {
      if (this.todos[i].isImportant) {
         emit(this.todos[i].date, {title: this.todos[i].title})
      }
   }
}

输出:

{
   key: 1502557780,
   value: {title: "Bring milk home."}
}

查询输出:

db.collection.find({key: { $lt: 1502557785 }}, ...

实际上,我想在映射函数中做一些更复杂的处理,而不是仅仅检查 isImportant 键的存在。因此,更复杂查询的聚合管道似乎不正确。

【问题讨论】:

    标签: mongodb mapreduce views


    【解决方案1】:

    在 MongoDb 中,您可以像这样使用Aggregation Pipeline Operators

    db.collection.aggregate(    
        [
            {
                $unwind: "$todos"
            },
            {
                $match: {
                    "todos.isImportant": true
                }
            },
            {
                $project: {
                    key: "$todos.date",
                    value: { title: "$todos.title" }
                }
            },
            {
                $match: {
                    key: { $lt: 1502557785 }
                }
            }
            // And so on ...
        ]
    );
    

    另一种方法是像这样使用Map-Reduce

    db.runCommand({ 
        mapReduce: "c",
        map: function () {
                    for (var i = 0; i < this.todos.length; i++) {
                        if (this.todos[i].isImportant) {
                            emit(this.todos[i].date, {title: this.todos[i].title})
                        }
                    }
                },
        reduce: function (key, values) {
                    return values;
                },
        out: { "inline" : 1},
        query: {},
        sort: {},
        limit: 100,
        inputDB: "Test",
     });
    

    【讨论】:

    • 是的,这绝对是在 MongoDB 中实现上述示例的一种方式。实际上,我想在每个文档上运行一个类似地图的函数,以进行更复杂的修改。
    • @Bernd 如果你想要更复杂的修改;所以你可以在回答中使用mapReduce 类似我的例子;)。
    猜你喜欢
    • 1970-01-01
    • 2012-11-11
    • 2014-02-01
    • 2011-12-12
    • 2021-02-05
    • 1970-01-01
    • 1970-01-01
    • 2013-11-16
    • 1970-01-01
    相关资源
    最近更新 更多