Node.js MongoDB 关联

关联集合

MongoDB 不是关系数据库,但可以使用 $lookup 执行左外关联(left outer join)。

$lookup 需要您指定要与当前集合合并的集合,以及应该匹配的字段。

考虑你有一个 "orders" 集合和一个 "products" 集合:

orders
  1. [
  2. { _id: 1, product_id: 154, status: 1 }
  3. ]
products
  1. [
  2. { _id: 154, name: 'Chocolate Heaven' },
  3. { _id: 155, name: 'Tasty Lemons' },
  4. { _id: 156, name: 'Vanilla Dreams' }
  5. ]
实例

将匹配的 "products" 文档加入到 "orders" 集合:

  1. var MongoClient = require('mongodb').MongoClient;
  2. var url = "mongodb://127.0.0.1:27017/";
  3. MongoClient.connect(url, function(err, db) {
  4. if (err) throw err;
  5. var dbo = db.db("mydb");
  6. dbo.collection('orders').aggregate([
  7. <strong> { $lookup:
  8. {
  9. from: 'products',
  10. localField: 'product_id',
  11. foreignField: '_id',
  12. as: 'orderdetails'
  13. }
  14. }
  15. </strong> ]).toArray(function(err, res) {
  16. if (err) throw err;
  17. console.log(JSON.stringify(res));
  18. db.close();
  19. });
  20. });

将上述代码保存在名为 "demo_mongodb_join.js" 的文件中,然后运行该文件:

运行 "demo_mongodb_join.js"

C:\Users\ Your Name >node demo_mongodb_join.js

结果如下:

  1. [
  2. { "_id": 1, "product_id": 154, "status": 1, "orderdetails": [
  3. { "_id": 154, "name": "Chocolate Heaven" } ]
  4. }
  5. ]

从上面的结果可以看出,products 集合中的匹配文档作为数组包含在 orders 集合中。

分类导航