入手MongoDB第一天,发现跟关系型数据库差别也不算太大。比较有意思的是$lookup联表查询。
自己总结了一下,比较土,但是易于理解。(好多资料都是直接复制官方文档原话。)
{$lookup:
{
from:'products', //关联你需要查询的表2
localField:'product_id', //指定表1中的一个关键字段对应第三个参数
foreignField:'_id', //指定表2中的一个关键字段对应第二个参数
as:'orderLists' //查询时,当第二个参数满足第一个参数,则将集合添加进orderlists
}
}
加几条数据试试!
orders表:
{
"_id" : 1,
"product_id" : 154,
"status" : 1
}
{
"_id" : 2,
"product_id" : 155,
"status" : 1
}
products表:
{
"_id" : 154,
"name" : "笔记本电脑"
}
{
"_id" : 155,
"name" : "耳机"
}
{
"_id" : 156,
"name" : "台式电脑"
}
来查一下:用的Node.js语法,都大同小异。
const MongoClient = require('mongodb').MongoClient
const url = 'mongodb://localhost:27017';
MongoClient.connect(url, { useNewUrlParser: true }, function (err, db) {
if (err) throw err;
console.log("runoob库已创建!")
var dbo = db.db("runoob");
dbo.collection("orders").aggregate([
{$lookup:
{
from:'products', //关联查询表2
localField:'product_id', //关联表1的商品编号ID
foreignField:'_id', //匹配表2中的ID与关联表1商品编号ID对应
as:'orderLists' //满足 localField与foreignField的信息加入orderlists集合
}
},
{$match:{"product_id":154}}//筛选类似与SQL的where
]).toArray(function(err,res){
if(err)throw err;
console.log(JSON.stringify(res))
db.close()
})
})
最后得出的结果: