【问题标题】:mongoose aggregate lookup with matching ObjectId具有匹配 ObjectId 的 mongoose 聚合查找
【发布时间】:2021-06-27 01:30:16
【问题描述】:

我有一个如下的猫鼬模式

var customers = new Schema({
    code: { type: String, required: true },
    companyName: { type: String, required: true }
});

var quotations = new Schema({
    quotationNo: { type: Number, required: true },
    customer: [
        { type: Schema.Types.ObjectId, ref: 'Customers' }
    ],
    quotationStatus: [
        { type: Schema.Types.ObjectId, ref: 'QuotationStatuses' }
    ],
})

var quotationStatuses = new Schema({
    quotationStatusName: { type: String, required: true }
});

我的收藏如下

Customers

{
"_id" : ObjectId("60517d3d8071452874926381"),
"code" : "M100003",
"companyName" : "Mongo Ltd"
}

Quotations

[
{
"_id" : ObjectId("605daf8609314910019239b1"),
"quotationNo" : "Q100000",
"customer" : "customer": [
    {
      "$oid": "60517d3d8071452874926381"
    }
 ],
 "quotationStatus": [
    {
      "$oid": "5fd03678926f57315414ebcb"
    }
  ],
},
{
"_id" : ObjectId("605daf860931491001923921"),
"quotationNo" : "Q100001",
"customer" : "customer": [
    {
      "$oid": "60517d3d8071452874926381"
    }
 ],
 "quotationStatus": [
    {
      "$oid": "5fd03766926f57315414ebcc"
    }
  ],
},
,
{
"_id" : ObjectId("605daf860931491001923956"),
"quotationNo" : "Q100002",
"customer" : "customer": [
    {
      "$oid": "60517d3d8071452874926381"
    }
 ],
 "quotationStatus": [
    {
      "$oid": "5fd03678926f57315414ebcb"
    }
  ]
}
]

QuotationStatuses

[{
  "_id": {
    "$oid": "5fd03678926f57315414ebcb"
  },
  "quotationStatusName": "FIRST SUBMISSION",
  "__v": 0
},{
  "_id": {
    "$oid": "5fd03766926f57315414ebcc"
  },
  "quotationStatusName": "REVISE SUBMISSION",
  "__v": 0
}]

我想获取所有报价状态为“FIRST SUBMISSION”的报价。所以我尝试了如下查询

Customers.aggregate([
    {
      $lookup: {
        from: "quotations",
        let: {
          "customerID": "$_id"
        },
        pipeline: [
          {
            $match: {
              $expr: {
                $and: [
                  {
                    $eq: ["quotationStatus":"5fd03678926f57315414ebcb"]
                  }
                ]
              }
            }
          }
        ],
        as: "quotations"
      }
    }
  ])

但运气不好,我无法得到答案。

quoteStatus 与 ObjectId 匹配时,不返回任何结果。

每个人都可以建议我哪里出错了。

谢谢

【问题讨论】:

    标签: mongoose aggregate lookup


    【解决方案1】:

    我认为您应该将 id 作为 ObjectId('5fd03678926f57315414ebcb') 传递给管道。因为,聚合函数接受它作为一个字符串。

     $and: [
            {
                $eq: [ "quotationStatus": mongoose.Types.ObjectId("5fd03678926f57315414ebcb") ]
            }
        ]
    

    【讨论】:

      猜你喜欢
      • 2020-06-29
      • 1970-01-01
      • 2016-10-14
      • 2016-07-11
      • 2018-09-17
      相关资源
      最近更新 更多