MongoDB: 没有reduce的映射?

MongoDB: Mapping without reduce?

我想创建一个地图并查询它。我来自 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 中,您可以像这样使用 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",
 });