2017-08-12 118 views
0

我想创建一个映射并进行查询。我来自CouchDB,它允许使用视图。 这与MongoDB可能的东西是一样的,是增量式地图/减少正确的事情?MongoDB:映射没有减少?

示例:取一些文档,并在处理结果并查询结果后,按照每个待处理的日期排出一行。

文献:

{ 
    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键的存在。所以更复杂的查询的聚合管线似乎并不正确。

回答

0

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", 
}); 
+0

是的,这是indead的方式实现上面的例子在MongoDB中。实际上,我想在每个文档上运行类似地图的功能以进行更复杂的修改。 – Bernd

+0

@Bernd如果你想要更复杂的修改;所以你可以在我的答案中使用'mapReduce'类似的例子;)。 –