MongoDB $lookup 管道匹配 _id 不起作用

2023-11-24

我正在尝试做一个$lookup在集合中并将一些数据添加到我的文档中。问题是当我尝试匹配我的$lookup管道由_id它返回一个空数组。这是我的代码:

Schedule.aggregate([{ // My Schedule schema
  $match: {
    store: req.query.store,
    "customer.id": req.query.user
  }
},
{
  $skip: +req.query.skip
}, {
  $limit: +req.query.limit
},
{
  $lookup: {
    from: Employee.collection.name, // "employee" schema,
    let: {
      id: "$employee.id" // employee _id from the "schedule" collection match above
    },
    pipeline: [{
        $match: {
          $expr: {
            "_id": "$$id" // here i try to match by _id
          }
        }
      },
      {
        $project: { // the only fields i need
          "_id": 1,
          "avatar": 1,
          "name": 1
        }
      }
    ],
    as: "employees" // employees is returned as []
  }
}
]).exec((err, resolve) => {
  if (err) console.log('error', err);
  res.json(resolve);
});

如果有帮助的话,这是我在此聚合中使用的两个集合:

时间表架构:

const ScheduleSchema = new Schema({
  store: {
    type: String,
    required: true
  },
  customer: {
    id: {
      type: String
    },
    name: {
      type: String
    },
    avatar: String,
    phone: {
      type: String
    },
    email: { type: String },
    doc: {
      type: String
    },
  },
  employee: {
    id: {
      type: mongoose.Schema.Types.ObjectId,
      required: true
    },
    name: {
      type: String,
      required: true
    },
    avatar: String,
  },
  service: {
    id: {
      type: String
    },
    name: {
      type: String,
      required: true
    },
    filters: [String]
  },
  info: {
    channel: {
      type: String,
      required: true,
      default: 'app'
    },
    id: mongoose.Schema.Types.ObjectId,
    name: String
  },
  scheduleDate: {
    type: String,
    required: true
  },
  scheduleStart: {
    type: String,
    required: true
  },
  scheduleEnd: {
    type: String,
    required: true
  },
  value: {
    type: Number
  },
  comissionType: {
    type: String,
    default: '$'
  },
  comissionValue: {
    type: Number,
    default: 0
  },
  status: {
    type: Number,
    required: true
  },
  observation: String,
  paymentMethod: {
    type: Number,
    default: 0
  },
  paymentValue: String,
  paymentChange: String,
  color: String
}, {
    timestamps: {
      createdAt: 'created',
      updatedAt: 'updated'
    }
  });

员工架构:

const EmployeeSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  a_to_z: String, // nome normalizado, só minusculas e sem espaços
  description: String,
  email: {
    type: String,
    required: true
  },
  avatar: String,
  phone: {
    type: String
  },
  storeOwner: {
    type: Boolean,
    required: true
  },
  permissions: [
    {
      route: String,
      hasPermission: Boolean
    }
  ],
  scheduleAutomatic: {
    type: Boolean,
    required: true,
    default: false
  },
  password: {
    passwordHash: String,
    salt: String
  },
  active: {
    type: Boolean,
    default: true
  },
  storeKey: {
    type: String,
    required: true
  },
  notification_token: String,
  notification_tokens: {
    type: [String],
    default: []
  },
  workingHours: [{
    weekDay: {
      type: Number,
    },
    doesWork: {
      type: Boolean,
    },
    startHour: String,
    endHour: String,
    lunchStart: String,
    lunchEnd: String
  }],
  config: {
    available_days: {
      type: Number,
      default: 365
    },
    in_advance_schedule: {
      type: Number,
      default: 0
    },
    in_advance_interval: {
      type: String,
      default: 'minute'
    }
  }
}, {
  timestamps: {
    createdAt: 'created',
    updatedAt: 'updated'
  } 
});

EDIT

The result i'm trying to achieve is this: Result example

The employees财产是我正在尝试使用的财产$lookup得到,它将具有与employee属性,最终它将是一个对象数组,其中只有一个对象。

一些示例文档:

日程:

color: "lavander",
created: "2018-07-31T18:50:53.423Z",
customer: {id: "5b60a67206e8a65f48a15f13", name: "Gabriel Barreto", phone: "11995274098", cpf: "40735255814"},
employee: {id: "5b2952c68424872fccece7f5", name: "Gabriel Barreto", avatar: null},
observation: "teste",
scheduleDate: "2018-08-01",
scheduleEnd: "2018-08-01 08:30",
scheduleStart: "2018-08-01 08:00",
service: {filters: Array(3), id: "5b606e8cc59e82354cc931e2", name: "Corte Masc"},
status: 1,
store: "5b16cceb56a44e2f6cd0324b",
updated: "2018-11-27T13:27:40.310Z",
value: 25,
__v: 0,
_id: "5b60af8de558661acc5d70b9"

员工:

a_to_z: "gabrielbarreto",
active: true,
avatar: "gabriel_barreto_h7qvcn.jpg",
config: {available_days: 180, in_advance_schedule: 10, in_advance_interval: "hour"},
created: "2018-06-19T19:00:22.315Z",
currency: "BRL",
description: "Novo perfil",
email: "[email protected]",
lang: "pt-BR",
name: "Gabriel Barreto",
notification_token: "2d768670-6011-4873-846d-39580b0d82d0",
notification_tokens: ["53049a82-53dc-4bc3-9646-7a4bee1f367b"],
password: null,
permissions: (10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}],
phone: "11995274098",
scheduleAutomatic: false,
storeKey: "5b16cceb56a44e2f6cd0324b",
storeOwner: true,
token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImdhYnJpZWwuYmFycmV0b0B3YWJpei5jb20uYnIiLCJpYXQiOjE1NTA2NzEwNDQsImV4cCI6MTU1MzI2MzA0NH0.0Odizd8pS4WPGSqm_2_XrTw1YE8NMOOXnHIrG-WVxGo",
updated: "2019-02-20T13:34:20.619Z",
workingHours: (8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}],
__v: 0,
_id: "5b2952c68424872fccece7f5"

谢谢你的时间


在将 $lookup 与 mongoose 一起使用来尝试匹配 _id 时,我也遇到了麻烦,因为我的集合将引用存储为字符串而不是 ObjectId

模型A:{_id:ObjectId(“xxx”),b_id:“eeeee”}

模型 B: {_id: ObjectId("eeeee")}

MyCollectionA.aggregate([
   {
      $lookup: {
        from: "collectionb",
        let: {id: "$b_id"},
        pipeline: [{$match: {$expr: {$eq: ["$_id", "$$id"]}}}],
        as: b
      }
])

在此示例中,b 从未被填充,因为 $$id 不被视为 ObjectId

只需添加一个项目来转换 objectId 中的 $$id 及其工作

MyCollectionA.aggregate([
   {
      $lookup: {
        from: "collectionb",
        let: {id: "$b_id"},
        pipeline: [
           {$project: {_id: 1, bid: {"$toObjectId": "$$id"}}},
           {$match: {$expr: {$eq: ["$_id", "$bid"]}}}
        ],
        as: b
      }
])

或者使用foreignField、localField:

MyCollectionA.aggregate([
   {
      $project:{
        _id: 1,
        b_id: {"$toObjectId": "$b_id"}
      }
   },
   {
      $lookup: {
        from: "collectionb",
        localField: "b_id",
        foreignField: "_id",
        as: b
      }
])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

MongoDB $lookup 管道匹配 _id 不起作用 的相关文章

随机推荐

  • SQL LIKE 语句的 LINQ 版本

    我是 LINQ 的新手 在网上搜索模仿 SQL 的 LIKE 语句的 LINQ 示例并不能让我满意 我想要的是产生与此 SQL 相同的查询结果 SELECT FROM table 1 WHERE column 1 LIKE 0 我想从 ta
  • Neo4j:MERGE 创建重复节点

    我的数据库模型有用户和 MAC 地址 一个用户可以有多个MAC地址 但一个MAC只能属于一个用户 如果某个用户设置了他的 MAC 并且该 MAC 已经链接到另一个用户 则现有关系将被删除 并在新所有者和该 MAC 之间创建新关系 换句话说
  • 在 Swing 应用程序中使用 Hibernate 进行会话管理

    如何在 Java Desktop Swing 应用程序中进行 Hibernate 会话管理 您使用单个会话吗 多次会议 以下是有关该主题的一些参考资料 http www hibernate org 333 html http blog sc
  • 围绕多个插入或更新使用事务的正确方法

    测试插入 更新失败并回滚此事务 如果有 的正确方法是什么 我认为我所拥有的不起作用 因为我的插入 更新是 3 个单独的语句 并且 ROWCOUNT 将仅反映最后执行的语句 BEGIN TRANSACTION Script GO INSERT
  • php isset() 在 javascript 中等效

    我正在寻找与 php 函数等效的 javascriptisset 我已经尝试过此处描述的方法JavaScript isset 等效项但在 firebug 中 出现错误 data del is undefined Firebug warnin
  • 使用 awk 从 stdin 或文件读取

    到目前为止 这是我的代码 awk a length END for i in a print i a i lt 1 sort n 它从文本文件中读取行的长度 并输出行的长度 然后输出有多少行具有相同的长度 所以输入 hello guys h
  • Passport.js - 隐式将 {user: req.user} 传递给模板?

    现在在多个项目中使用 Passport js 和 Express 我注意到自己一遍又一遍地这样做 即指定 user req user 明确用于我的 Express 路线 有时我忘记传递它 突然之间就像用户甚至不再登录一样 我怎样才能通过us
  • “……”标记是什么意思?即参数包上的双省略号运算符

    在浏览 gcc 当前对新 C 11 标头的实现时 我偶然发现了 标记 您可以检查以下代码编译良好 来自 godbolt org template
  • MapReduce 中的叉积

    我想使用 Java MapReduce 在 Hadoop 中的两个数据集上执行昂贵的叉积操作 例如 我有数据集 A 和数据集 B 中的记录 并且我希望输出中数据集 A 中的每条记录与数据集 B 中的每条记录相匹配 我意识到它的输出大小是 A
  • QML:将滚动条附加到ListView

    我在使用 ListView 时遇到问题 ListView 太长 部分出现在窗口之外 但我无法附加滚动条 我尝试了很多不同的组合 我认为问题在于高度参数 但如果删除它 ListView 仅显示第一个条目 Column anchors fill
  • 自定义 UITableViewCell 内的 UISwitch 不可用

    我有一个UISwitch自定义里面UITableViewCell 我称之为的子类RootLabeledSwitchTableCell 该细胞含有一个UILabel and UISwitch彼此相邻 我有一个 property called
  • Hql,如何在具有一对多关系的表之间编写联接查询?

    I have 2表 1st一个有oneToMany有关系2nd 班级作者 Entity Table name Author Public class Author Id Column name AuthorId private int au
  • 如何将进程输出通过管道传送到 Windows 和 JDK 6u45 上的文件

    我有以下 Windows 批处理文件 run bat echo off echo hello batch file to sysout 以下 java 代码运行批处理文件并将输出重定向到文件 public static void main
  • 像 Firefox 一样制作带有标题的 JPanel 边框

    我想在我的应用程序中创建一个选项对话框 在此对话框中 我想创建一种由边框和标题包围的区域 我想要的一个例子是在 Firefox 中 我怎样才能在Java中做类似的事情呢 Here您可以找到您需要的所有信息 基本上 您可以使用边框工厂使用 S
  • 清除Android毕加索图片库的磁盘/SD卡缓存

    我正在使用 Picasso 从我的服务器加载图像 它工作正常 但我正在加载图像 并稍后更改它 但是Picasso将图像缓存在磁盘中的某个位置 我检查了SD卡 没有找到Picasso存储的任何目录 我尝试按照此问题的已接受答案的建议删除缓存
  • 简单的 Zlib C++ 字符串压缩和解压缩

    我需要在 C 中对 std string 进行简单的压缩和解压缩 我看了这个site代码适用于字符数组 我想要实现的是两个功能 std string original This is to be compressed std string
  • 将邪恶的抽象 Ajax 行为与 jQuery.ajax() 一起使用

    我已经使用 jQuery AJax 调用来发送 JSON 如此处所述堆栈溢出 问题是我没有在服务器上收到任何数据 我可以看到调用确实达到了目标ajax行为 但是在onRequest 方法中 RequestCycle dd不包含任何参数 我的
  • 如何在 Windows 中使用 MinGW 的 CLion 中的 C 项目中使用 pthread 头文件

    我正在尝试包括 include
  • XmlDocument.Load 失败,LoadXml 工作:

    在回答中这个问题 我遇到了一个我不明白的情况 OP 尝试从以下位置加载 XML 显而易见的解决方案是 string m strFilePath http www google com ig api weather 12414 hl it X
  • MongoDB $lookup 管道匹配 _id 不起作用

    我正在尝试做一个 lookup在集合中并将一些数据添加到我的文档中 问题是当我尝试匹配我的 lookup管道由 id它返回一个空数组 这是我的代码 Schedule aggregate My Schedule schema match st