{ _id: 155, name: '耳机' },
{ _id: 156, name: '台式电脑' }
]
$lookup 实现左连接
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://127.0.0.1:27017/";MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
if (err) throw err;
var dbo = db.db("runoob");
dbo.collection('orders').aggregate([
{ $lookup:
{
from: 'products', // 右集合
localField: 'product_id', // 左集合 join 字段
foreignField: '_id', // 右集合 join 字段
as: 'orderdetails' // 新生成字段(类型array)
}
}
]).toArray(function(err, res) {
if (err) throw err;
console.log(JSON.stringify(res));
db.close();
});
});
删除集合
我们可以使用 drop() 方法来删除集合:
drop()
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
if (err) throw err;
var dbo = db.db("runoob");
// 删除 test 集合
dbo.collection("test").drop(function(err, delOK) { // 执行成功 delOK 返回 true,否则返回 false
if (err) throw err;
if (delOK) console.log("集合已删除");
db.close();
});
});









