有谁知道如何在 PouchDB 数据库上创建聚合函数,例如 avg、sum、max 和 min。我创建了一个简单的应用程序来测试 PouchDB。我仍然不知道如何运行这些命令。提前致谢。
例如。如何获得“数字”字段的最高、最低或平均值?
My main Ionic 2 component
import {Component} from '@angular/core';
import {Platform, ionicBootstrap} from 'ionic-angular';
import {StatusBar} from 'ionic-native';
import {HomePage} from './pages/home/home';
declare var require: any;
var pouch = require('pouchdb');
var pouchFind = require('pouchdb-find');
@Component({
template: '<ion-nav [root]="rootPage"></ion-nav>'
})
export class MyApp {
rootPage: any = HomePage;
db: any;
value: any;
constructor(platform: Platform) {
platform.ready().then(() => {
StatusBar.styleDefault();
});
pouch.plugin(pouchFind);
this.db = new pouch('friendsdb');
let docs = [
{
'_id': '1',
'number': 10,
'values': '1, 2, 3',
'loto': 'fooloto'
},
{
'_id': '2',
'number': 12,
'values': '4, 7, 9',
'loto': 'barloto'
},
{
'_id': '3',
'number': 13,
'values': '9, 4, 5',
'loto': 'fooloto'
}
];
this.db.bulkDocs(docs).then(function (result) {
console.log(result);
}).catch(function (err) {
console.log(err);
});
}
}
ionicBootstrap(MyApp);
最佳答案
可以使用内置的 _stats reduce 函数检索数字字段的最高值和最低值。
var myMapReduceFun = {
map: function (doc) {
emit(doc._id, doc.number);
},
reduce: '_stats'
};
db.query(myMapReduceFun, {reduce: true}).then(function (result) {
// handle result
}).catch(function (err) {
// handle errors
});
结果类似于:
{"sum":35,"count":3,"min":10,"max":13,"sumsqr":214}
最高值在“max”字段中,最低值在“min”字段中。现在你只需要计算你想要的平均值,例如平均值:
var meanAverage = result.sum / result.count;
其他built-in reduce functions在 PouchDB 中是 _count 和 _sum。
PouchDB documentation说了以下关于减少功能的内容:
Tip: if you’re not using a built-in, you’re probably doing it wrong.
关于javascript - 如何在PouchDB上模拟聚合函数avg、sum、max、min、count?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38779998/