Node.js MongoDB Join
Join Collections
MongoDB 不是一个关系型数据库,但你可以使用 $lookup
阶段来执行左外连接。
The $lookup
stage lets you specify which collection you want to join with the current collection, and which fields that should match.
Consider you have a "orders" collection and a "products" collection
orders(订单)
[
{ _id: 1, product_id: 154, status: 1 }
]
products(产品)
[
{ _id: 154, name: 'Chocolate Heaven' },
{ _id: 155, name: 'Tasty Lemons' },
{ _id: 156, name: 'Vanilla Dreams' }
]
示例
Join the matching "products" document(s) to the "orders" collection
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://127.0.0.1:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
dbo.collection('orders').aggregate([
{ $lookup:
{
from: 'products',
localField: 'product_id',
foreignField: '_id',
as: 'orderdetails'
}
}
]).toArray(function(err, res) {
if (err) throw err;
console.log(JSON.stringify(res));
db.close();
});
});
运行示例 »
Save the code above in a file called "demo_mongodb_join.js" and run the file
Run "demo_mongodb_join.js"
C:\Users\Your Name>node demo_mongodb_join.js
这将产生以下结果:
[
{ "_id": 1, "product_id": 154, "status": 1, "orderdetails": [
{ "_id": 154, "name": "Chocolate Heaven" } ]
}
]
As you can see from the result above, the matching document from the products collection is included in the orders collection as an array.