概述
MONGODB, NODEJS聚合简单例子
Mongodb 聚合
所需mongodb 本地 安装
node js 本地安装
程序分析
其实也没什么分析。代码说明了一切
var mongoose = require('mongoose'); //mongoo中间件
var Schema = mongoose.Schema; //数据模型
//Database connection 数据库连接
var uristring = 'mongodb://localhost/test';
var mongoOptions = {};
mongoose.connect(uristring, mongoOptions, function (err, res) {
if (err) {
console.log('Error when connecting to: ' + uristring + '. ' + err);
}
else {
console.log('Successfully connected to: ' + uristring);
}
});
//建立两个模型。Record, Account
//First let's create the Schemas:
// Record Schema
var Record = new Schema({
amount: { type: Number, required: true },
date: { type: Date, required: true },
description: { type: String }
})
// Account Schema
var Account = new Schema({
name: { type: String, required: true },
currency: { type: String, required: true },
created: { type: Date, default: Date.now },
records: [Record]//嵌套Record模型
});
//Define Models
var AccountModel = mongoose.model('Account', Account);
var RecordModel = mongoose.model('Record', Record);
var ObjectId = require('mongoose').Types.ObjectId;
// Utility functions to insert data: 插入测试数据.
//一条数据叫:DOCUMENT
var insertAccount = function (account, callback) {
var Account = new AccountModel();
Account.name = account.name;
Account.currency = account.currency;
Account.records = [];
Account.save(function (err) {
if (err) {
console.log(err);
return null;
}
return callback(Account._id);//完成插入之后的回调
});
}
//根据所给accountId, 插入多个Record
//一个Account模型可以插入多个Record
var insertRecords = function (accountId, record, numberOfRecords, callback) {
AccountModel.findOne({ _id: accountId }, function (err, account) {
if (err) {
console.log(err);
return;
}
for (var i = 0; i < numberOfRecords; i++) {
var Record = new RecordModel();
Record.amount = record.amount;
Record.date = new Date();
Record.is_expense = record.is_expense;
account.records.push(Record);
}
account.save(function (err2) {
if (err2) {
console.log(err2);
}
return callback();
});
});
}
//查询数据库的整个COLLECTION。未用到
var listAccounts = function () {
var query = AccountModel.find();
query.exec(function (err, accounts) {
if (err) {
console.log(err);
}
console.log(accounts);
});
}
//查询单个DOCUMENT
var listAccount = function (id) {
if (id == null) {
return;
}
var query = AccountModel.find({ _id: id });
query.field('_id name currency date');
query.exec(function (err, accounts) {
if (err) {
console.log(err);
}
console.log(accounts);
});
}
//移除单个document。未用到
var removeAccount = function (accountId) {
var query = AccountModel.findOne({ _id: accountId });
query.exec(function (err, account) {
if (err) {
console.log(err);
return;
}
account.remove();
});
}
//Aggregation function 聚合查询balance
var getBalance = function (accountId) {
AccountModel.aggregate([
{//先是匹配,匹配字段为accountId
$match: {
_id: accountId
}
},//多个动作
{ $unwind: "$records" },//查询完成之后回绕
{
$group: {//聚合数据
_id: "$_id",按条件聚合。字段依然为_id。整个collection了
//计算SUM。计算字段为account.records.amount
balance: { $sum: "$records.amount" }
}
}
], function (err, result) {//回调包括出错和结果
if (err) {
console.log(err);
return;
}
console.log(result);
});
}
//Let's add some data and call the getBalance fucntion
//插入一条account数据
insertAccount({ name: "First Account", currency: "Dollar" }, function (accountId) {
if (accountId == null) {
console.log("accountId is null");
return;
}
//以上插入完成之后得到accountId。
//根据该accountId,插入1000条Record数据
insertRecords(accountId, { amount: 123.5 }, 1000, function () {
//插入完成之后,查询并控制台打印balance
getBalance(accountId);
});
});
//疑问:干嘛要两次插入? 完全可以一次插入完整数据
最后
以上就是安静荷花为你收集整理的MONGODB, NODEJS聚合简单例子Mongodb 聚合的全部内容,希望文章能够帮你解决MONGODB, NODEJS聚合简单例子Mongodb 聚合所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复