注:閱讀此篇文章,需要有一定的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;