node.js - 如何在 mongodb 中创建嵌套查找?
问题描述
我想加入 3 张桌子。这是我的汇总,它只是加入第一个和第二个表。
const products = await ProductInventory.aggregate([
{
$lookup: {
from: 'productdetails',
localField: 'prodId',
foreignField: '_id',
as: 'product',
},
},
{
$unwind: '$product',
},
{
$match: { 'product.isActive': 'Yes' },
},
]);
这是上面代码的结果。在产品中,我有一个类别及其类别的 ID。我也想在类别表中加入它。所以我可以得到类别名称。
"products": [
{
"_id": "60a0e77b02a58f3038598301",
"prodId": "TB-057",
"stock_onhand": "30",
"date_created": "2021-05-16T09:35:55.565Z",
"date_updated": "2021-05-16T09:35:55.565Z",
"__v": 0,
"product": {
"_id": "TB-057",
"isActive": True,
"product_name": "TEST2",
"unit_price": "1.23",
"markup_price": "1.23",
"SRP": "2.46",
"description": "test2",
"category": "609521209d10ac4774748c74",
"date_updated": "2021-05-16T09:35:55.562Z",
"date_created": "2021-05-16T09:35:55.565Z",
"__v": 0
}
},
使用 $unwind: '$product' 后是否应该再次使用查找?
//SAMPLE DOCUMENTS
//This is the productinventories
"_id" : ObjectId("609d398829be8e2bd8509d6e"),
"prodId" : "TB-056",
"stock_onhand" : "12",
"date_created" : ISODate("2021-05-13T14:36:56.730Z"),
"date_updated" : ISODate("2021-05-13T14:36:56.730Z"),
"__v" : 0
//This is the productdetails
"_id" : "TB-056",
"isActive" : True,
"product_name" : "TEST",
"unit_price" : "1.23",
"markup_price" : "1.23",
"SRP" : "2.46",
"description" : "maiba 1",
"category" : ObjectId("609521209d10ac4774748c74"),
"date_updated" : ISODate("2021-05-13T14:36:56.728Z"),
"date_created" : ISODate("2021-05-13T14:36:56.730Z"),
"__v" : 0
//this is the categories
"_id" : ObjectId("609521209d10ac4774748c74"),
"isActive" : True,
"category_name" : "TABLET",
"category_abbreviation" : "TB",
"date_updated" : ISODate("2021-05-07T11:14:40.544Z"),
"date_created" : ISODate("2021-05-07T11:14:40.544Z"),
"__v" : 0
解决方案
是的,$lookup
如果您想从第三个集合中获取数据,您需要再次运行。
在你的情况下:
const products = await ProductInventory.aggregate([
{
$lookup: {
from: 'productdetails',
localField: 'prodId',
foreignField: '_id',
as: 'product',
},
},
{
$unwind: '$product',
},
{
$match: { 'product.isActive': 'Yes' },
},
{
$lookup: {
from: 'categories',
localField: 'product.category',
foreignField: '_id',
as: 'category',
},
},
{
$unwind: '$category',
}
]);
推荐阅读
- vue.js - 在开发模式下为 vue 组件/模板添加检查
- elasticsearch - Elasticsearch:嵌套 VS 扁平索引
- javascript - tic tac toe 如何保持比赛直到胜利或平局
- dart - 如何在 Dart 的 DateTime 中获取 N 天前?
- r - 如果指定了多个 repos,install.packages 的行为是什么?
- java - 区别:字符 >= '0' 和字符 <= 0
- reactjs - Redux - 从相关状态中删除实体
- python - 在 virtualenv 中运行 tensorflow 时出错:模块 'tensorflow' 没有属性 'truncated_normal'
- sql - 将 MERGE 语句转换为 UPDATE 语句
- python - 从作为 csv 文件一部分的字符串中修剪不同子字符串的列表