【问题标题】:Mongo Groupby Aggregate Based on "Key" Not ValueMongo Groupby 基于“键”而非值的聚合
【发布时间】:2017-03-17 08:03:14
【问题描述】:

我被 mongo 查询卡住了。我有一个 mongo 集合结构,目前无法修改,因为它是非常大的数据。

我需要从集合中执行一些结果,所以尝试了各种方法来获得它。

这是我的集合 json 架构:-

{
    "date": "2017-01-01T00:00:00.000Z",
    "bob":"P",
    "jacob":"P",
    "wilson":"A",
    "dev":"SL"
},
{
    "date": "2017-01-02T00:00:00.000Z",
    "bob":"P",
    "jacob":"A",
    "wilson":"A",
    "dev":"SL"
},
{
    "date": "2017-01-03T00:00:00.000Z",
    "bob":"P",
    "jacob":"P",
    "wilson":"A",
    "dev":"SL"
},
{
    "date": "2017-01-04T00:00:00.000Z",
    "shashikant":"P",
    "jacob":"P",
    "wilson":"SL",
    "dev":"SL"
}
....

作为输出,我正在寻找以下结构:-

from 1st jan 2017 to 30th jan 2017

    bob      P      17
    bob      A      2
    wilson   P      10
    dev      SL.    1
    .....

我正在为我的后端使用环回,但我仍然可以使用普通的 mongodb 查询来获取输出。

请帮忙

【问题讨论】:

    标签: node.js mongodb mongoose mongodb-query loopbackjs


    【解决方案1】:

    MongoDB 只允许对数组使用 $unwind。但是你可以使用一个简单的mapReduce 来实现你想要的:

    //Define the time frame here
    var from = new Date('2015-01-01T00:00:00.000Z');
    var to = new Date('2025-01-01T00:00:00.000Z');
    
    db.getCollection('test').mapReduce(function () {
    		var keys = Object.keys(this);
    
    		//If there is no date found on a record, simply skip
    		if (!this.date) {
    			return;
    		}
    
    		var date = new Date(this.date);
    
    		//Skip the records that do not fit into [form; to] interval
    		if (!(date >= from && date <= to)) {
    			return;
    		}
    
    		for (var i = 0; i < keys.length; i++) {
    			var key = keys[i];
    
    			//Emit each combination of key and value
    			if (key !== 'date' && key !== '_id') {
    				emit({key: key, value: this[key]}, {count: 1});
    			}
    		}
    	},
    
    	function (key, values) {
    		var reduced = {count: 0};
    
    		for (var i = 0; i < values.length; i++) {
    			var value = values[i];
    
    			//Simply counting the combinations here
    			reduced.count += value.count;
    		}
    
    		return reduced;
    	},
    	{
    		//Passing the dates to mongo
    		//so 'from' and 'to' will be avail in map, reduce and finalize
    		scope: {from: from, to: to},
    		finalize: function (key, reducedValue) {
    			//Changing the data structure just for a convenience
    			return {
    				propertyName: key.key,
    				propertyValue: key.value,
    				from: from,
    				to: to,
    				count: reducedValue.count
    			};
    		},
    		out: {inline: 1}
    	}
    );

    我在 Mongo 控制台中对此进行了测试,但 mongo 本机 Node.js 和 mongoose 也支持 map-reduces。

    【讨论】:

      猜你喜欢
      • 2020-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-12
      • 2018-07-05
      • 2021-10-10
      • 1970-01-01
      相关资源
      最近更新 更多