Nodejs mongoose项目 ,聚合查询的代码问题

Nodejs mongoose项目 ,聚合查询的代码问题

Robomongo的聚合查询如下:

db.accounts.aggregate([ { $match: { “date”: {"$gte" : “2014/07/01” , “$lte” : “2014/07/31”}} }, { $group: { _id: “$kind.code_no”, total: { $sum: “$cash” } } }, { $sort: { total: -1 } } ])

查出数据:###

{ “result” : [ { "_id" : “income”, “total” : 1000 }, { "_id" : “payout”, “total” : 300 } ], “ok” : 1 }

node方法中的代码如下,Accounts是model

Accounts.aggregate([ { $match: { “date”: {"$gte" : firtday , “$lte” : endday}} }, { $group: { _id: “$kind.code_no”, total: { $sum: “$cash” } } }, { $sort: { total: -1 } } ],function (err, docs) { if (err) { return callback(err); } return callback(null, docs); });

查询后直接加的回调函数。。。。大家都怎么用聚合查询然后执行回调函数的。###


5 回复

当然,可以帮您解答这个问题。首先,我们需要理解Mongoose是如何处理聚合查询的,并确保您的代码能够正确地实现预期的功能。

聚合查询的背景

聚合查询是一种强大的工具,用于对MongoDB数据库中的数据进行复杂的分析。在您的案例中,您希望根据特定日期范围内的现金总额对账户数据进行分组和排序。

示例代码及解析

1. 数据库配置和模型定义

假设您已经有一个名为Account的Mongoose模型,并且它映射到名为accounts的集合。以下是模型的一个简化版本:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const accountSchema = new Schema({
    date: Date,
    kind: {
        code_no: String
    },
    cash: Number
});

const Account = mongoose.model('Account', accountSchema);

2. 执行聚合查询

接下来,我们使用Mongoose的aggregate方法来执行聚合查询。这需要一个数组作为参数,该数组包含一系列聚合管道操作。每个管道操作是一个对象,定义了如何处理文档流。

const firtday = new Date("2014-07-01");
const endday = new Date("2014-07-31");

Account.aggregate([
    { $match: { "date": { "$gte": firtday, "$lte": endday } } },
    { $group: { _id: "$kind.code_no", total: { $sum: "$cash" } } },
    { $sort: { total: -1 } }
], function (err, result) {
    if (err) {
        console.error("Error executing aggregation:", err);
        return;
    }

    console.log(result); // 输出结果
});

3. 解释

  • $match: 这个阶段用于过滤文档,只保留那些满足指定条件(在这个例子中是日期范围)的文档。
  • $group: 使用$group阶段按kind.code_no字段对文档进行分组,并计算每个组的cash字段总和。
  • $sort: 最后一个阶段是对结果按total字段降序排序。

回调函数的使用

在Mongoose的aggregate方法中,第二个参数是一个回调函数,它接收两个参数:错误(如果有的话)和结果。如果发生错误,您应该处理它(例如,记录错误或向用户显示错误信息)。如果没有错误,则结果将包含聚合查询的结果。

通过这种方式,您可以有效地使用Mongoose执行复杂的聚合查询,并根据需要处理结果。


http://mongoosejs.com/docs/api.html#model_Model.aggregate 这里有API

另外请问下,你数据库日期存储的是格式, 我用的 毫秒,我现在很纠结,这个聚合怎么做。new MongoDate(1405360394, 499000) 你底层格式是怎么样的呢?

我这么一写查不出数据。妹的 db.sendinfo.aggregate([ { $match: { “create_at”: {"$gte" : “2014-07-01T17: 53: 14.499Z” , “$lte” : “2014-07-31T17: 53: 14.499Z”}} }, { $group: { _id: “$create_at”, total: { $sum: “$sendto” } } }, { $sort: { total: -1 } } ])

###我的底层格式date直接就是String类型的。### date : { type: String }

你的create_at用Date型( create_at: { type: Date, default: Date.now },) 你这么用就可以查出来了。 var start = new Date(2014, 6, 14);//2014年7月14日 var end = new Date(2014, 6, 31); //2014年7月31日,6代表7月,从0开始数 ,0-11 db.accounts.aggregate([ { $match: { “create_at”: {"$gte" : start , “$lte” : end}} }, { $group: { _id: “$kind.code_no”, total: { $sum: “$cash” } } }, { $sort: { total: -1 } } ])

这里有个帖子你可以看下:http://blog.csdn.net/laiahu/article/details/7590963

这里面东西可真多啊,前后顺序不同,结果就不同

根据你的描述,你希望使用 Mongoose 在 Node.js 中实现与 Robomongo 中类似的聚合查询,并通过回调函数处理结果。

示例代码

假设你有一个名为 Accounts 的 Mongoose 模型,并且你已经定义好了日期变量 firtdayendday,你可以这样写聚合查询:

const mongoose = require('mongoose');
const Accounts = mongoose.model('Account', new mongoose.Schema({ /* 你的模型定义 */ }));

// 假设 firtday 和 endday 已经定义好
const firtday = new Date('2014-07-01');
const endday = new Date('2014-07-31');

Accounts.aggregate([
    { 
        $match: { 
            date: { 
                "$gte": firtday, 
                "$lte": endday 
            } 
        } 
    },
    { 
        $group: { 
            _id: "$kind.code_no", 
            total: { $sum: "$cash" } 
        } 
    },
    { 
        $sort: { 
            total: -1 
        } 
    }
], function (err, docs) {
    if (err) {
        console.error("Error executing aggregation:", err);
        return;
    }

    console.log("Aggregation results:", docs);
});

解释

  1. 引入 Mongoose:首先需要引入 Mongoose 并定义好你的 Accounts 模型。
  2. 定义日期范围:你需要定义两个日期变量 firtdayendday,分别表示查询的开始日期和结束日期。
  3. 聚合查询
    • $match 阶段用于过滤出指定日期范围内的文档。
    • $group 阶段将结果按 kind.code_no 分组,并计算每个分组的 cash 总和。
    • $sort 阶段按 total 字段降序排列结果。
  4. 回调函数:在聚合查询完成后,回调函数会接收到查询结果或错误信息。如果发生错误,则输出错误信息;否则,打印查询结果。

确保你已经正确设置了 Mongoose 连接到 MongoDB 数据库,并且 Accounts 模型已经定义好相应的字段和类型。

回到顶部