在 MongoDB 聚合中使用 $match 过滤结果返回空白数组

我有以下架构:

const UserQualificationSchema = new Schema(
    {
        user: {
            type: mongoose.Schema.Types.ObjectId,ref: 'User',},qualification: {
            type: mongoose.Schema.Types.ObjectId,ref: 'Qualification',expiry_date: {
            type: Date
        }
    }
const QualificationSchema = new Schema(
    {
        fleet: {
            type: [String],// Eg ["Fleeta","FleetB","FleetC"]
            required: true,}
    }

我正在使用表格中的过滤器搜索 UserQualifications,以按车队、资格或到期日期进行搜索。到目前为止,我有以下聚合:

db.UserQualifications.aggregate([{
{
    $lookup: {
      from: 'qualifications',localField: 'qualification',foreignField: '_id',as: 'qualification',{
  $unwind: '$qualification',{
  $match: {
    $and: [
      'qualification.fleet': {
         $in: ["Fleet A","Fleet C"],// This works
       },expiry_date: {
         $lt: req.body.expiry_date,qualification: { // Also tried 'qualification._id'
         $in: ["6033e4129070031c07fbbf29"] // Adding this returns blank array
      }
    ]
  },}
}])

按车队过滤和到期日期既可以独立也可以组合使用,但是当按资格 ID 添加时,尽管发送的 ID 是有效的,但它返回空白。

我在这里遗漏了什么吗?

WW30824 回答:在 MongoDB 聚合中使用 $match 过滤结果返回空白数组

查看您的架构,我可以推断出 ObjectId 中的限定条件,并且在查询中您只传递了 ObjectId 的字符串值。您可以传递 ObjectId 以获得预期的输出

db.UserQualifications.aggregate([
  {
    $lookup: {
      from: "Qualifications",localField: "qualification",foreignField: "_id",as: "qualification",},{
    $unwind: "$qualification",{
    $match: {
      "qualification.fleet": {
        $in: [
          "FleetA","FleetC"
        ],expiry_date: {
        $lt: 30 // some dummy value to make it work
      },"qualification._id": {
        $in: [
         // some dummy value to make it work
          ObjectId("5a934e000102030405000000") 
        ]
      }
    },}
])

我用一些虚拟数据创建了一个游乐场来测试查询:Mongo Playground

此外,在 $match 阶段,无需在 $and 中明确组合查询,因为默认情况下,行为将仅与 $and 相同,因此我已在查询中删除了该部分

本文链接:https://www.f2er.com/2387.html

大家都在问