【问题标题】:Mongoose ignoring empty fields while aggregatingMongoose 在聚合时忽略空字段
【发布时间】:2021-11-20 11:37:11
【问题描述】:

收藏:A

文档:

{
color: '',
age: 22,
name: 'John'
}

收藏:B

文档:

{
name:'John',
marks: 100
}

我通过像这样加入两个集合来执行聚合

A.aggregate([
    {
      $match: filters
    },
    {
      $lookup: {
        from: 'B',
        localField: 'name',
        foreignField: 'name',
        as: 'alias1',
      }
    },
    {
      $unwind: '$alias1'
    },
    {
      $project: {
        color: '$color',
        marks: '$alias1.marks',
       }
}])

我得到的结果是:

{
marks:100
}

我期待的结果是:

{
color: '',
marks: 100
}

我假设由于颜色字段为空,聚合默认忽略它。

基本上,我想连接两个表并获取几个字段的数据。如果聚合不能解决这个问题,那么任何其他实现预期结果的方法都会有很大帮助。谢谢。

【问题讨论】:

  • 聚合是否适用于非空color 字段?
  • @WernfriedDomscheit,但 alias1 不是对集合 B 字段的引用吗?
  • 您的样本按预期工作,请参阅mongoplayground.net/p/bd-F3iMADfP
  • 您的查询会产生您需要的结果see,但这假设从集合 B 中查找最大值为 1,否则您将需要 $group,请逐个尝试各个阶段以查看发生了什么。

标签: javascript node.js mongodb mongoose nosql


【解决方案1】:

尝试以下查询:

A.aggregate([
    {
      $match: filters
    },
    {
      $lookup: {
        from: 'B',
        localField: 'name',
        foreignField: 'name',
        as: 'alias1',
      }
    },
    {
      $unwind: '$alias1'
    },
    {
      $project: {
        color: { $ifNull: [ "$color", "" ] },
        marks: '$alias1.marks',
       }
}])

【讨论】:

    猜你喜欢
    • 2021-05-15
    • 2019-06-03
    • 2016-10-20
    • 2022-10-04
    • 2019-03-30
    • 2012-09-28
    • 2014-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多