Mongoose中的关联表查询 && 聚合查询

注:阅读此篇文章,需要有一定的Mongo基础。基本的不会再重复介绍。

 

例:  有两张表,一张是博客列表,另外一张是博客的标签表。现在我们要做两张表的插入和关联查询。

创建两张表的Schema

主表blog

//博客schema
var blogSchema = new mongoose.Schema({
    title: {type: String}, //博客题目
    abstract: {type: String}, //摘要
    content: {type: String}, //文章内容
    click: {type: Number},//点击量
    createtime: {type: String} //消费时间
})

//创建model,第三个参数是实际表名
var blogModel = db.model("blog", blogSchema, "blog");

子表label

//标签表
var labelSchema = new mongoose.Schema({
    blogid: {type: mongoose.Schema.Types.ObjectId, ref: 'blog'},//这里即为子表的外键,关联主表。  ref后的blog代表的是主表blog的Model。
    label: {type: String} //标签名
});

//创建model,第三个参数是实际表名
var labelModel = db.model("label", labelSchema, "label");

插入数据

//1.主表插入数据
blogModel.create({...}, function (err, doc) {
       if(err) return xxx;
       //2.子表插入数据。 blogid为刚插入主表的主键
labelModel.create({blogid: doc._id, label: label}, function (err, doc) {
if (err) return xxx;
       })
})

关联查询

//子表关联主表查询,populate里面为子表外键
labelModel.find({}).populate('blogid').exec(function(err,docs){
     
})

 

简单的表关联查询就是这样。  当然也可以用主表关联子表查询,那就需要修改两张表的Schema了。 外键应该定义在主表中,而不是上面例子的子表中。

 

聚合查询

SQL语句:    select count(1),label from table group by label 。

那么在mongo中我们该如何实现呢? 直接上例子

//MongoDB中聚合(aggregate)主要用于处理数据(诸如统计平均值,求和等),并返回计算后的数据结果; 注意_id,num_tutorial这两个字段都不能变(固定写法)
labelModel.aggregate([{$group : {_id : "$label", num_tutorial : {$sum : 1}}}],function(err,docs){
        console.log(docs)
    })

参考aggregate中文介绍:http://www.w3cschool.cc/mongodb/mongodb-aggregate.html;

posted @ 2015-06-09 17:41  半岛弥情  阅读(18043)  评论(0编辑  收藏  举报