【问题标题】:MongoDB query - unwind and match preserving null OR different value/ add a new field based on a conditionMongoDB查询-展开并匹配保留null或不同的值/根据条件添加新字段
【发布时间】:2020-03-18 16:24:30
【问题描述】:

如果 a 具有以下结构:

{
    _id: 1,
    name: 'a',
    info: []
},
{
    _id: 2,
    name: 'b',
    info: [
        {
            infoID: 100,
            infoData: 'my info'
        }
    ]
},
{
    _id: 3,
    name: 'c',
    info: [
        {
            infoID: 200,
            infoData: 'some info 200'
        },
        {
            infoID: 300,
            infoData: 'some info 300'
        }
    ]
}

我需要以这种方式查询以获取显示 infoData 的 infoID 为 100 的文档,或者 如果 info 为空,或者包含 infoID 不同的子文档从 100 起。

也就是说,我想要以下输出:

{
    _id: 1,
    name: 'a',
    infoData100: null
},
{
    _id: 2,
    name: 'b',
    infoData100: 'my info'
},
{
    _id: 3,
    name: 'c',
    infoData100: null
}

如果我 $unwind info$match infoID: 100,我会丢失记录 1 和 3。

感谢您的回复。

【问题讨论】:

  • 我认为你可以通过聚合来做到这一点,使用$filter 只选择你想要的数组元素,然后$cond$project 内设置最终值

标签: mongodb mongodb-query aggregation-framework


【解决方案1】:

试试下面的查询:

查询:

db.collection.aggregate([
  /** Adding a new field or you can use $project instead of addFields */
  {
    $addFields: {
      infoData100: {
        $cond: [
          {
            $in: [100, "$info.infoID"] // Check if any of objects 'info.infoID' has value 100
          },
          {
            // If any of those has get that object & get infoData & assign it to 'infoData100' field
            $let: {
              vars: {
                data: {
                  $arrayElemAt: [
                    {
                      $filter: {
                        input: "$info",
                        cond: { $eq: ["$$this.infoID", 100] }
                      }
                    },
                    0
                  ]
                }
              },
              in: "$$data.infoData"
            }
          },
          null // If none has return NULL
        ]
      }
    }
  }
]);

测试: MongoDB-Playground

【讨论】:

  • 很抱歉,我们的要求发生了变化,我不再需要上述查询。非常感谢您的回复,而且它似乎确实有效,所以我将其标记为有效(尽管我真的不知道它是如何工作的哈哈)。
猜你喜欢
  • 2023-02-14
  • 2022-11-26
  • 1970-01-01
  • 1970-01-01
  • 2020-12-15
  • 2022-12-10
  • 2011-06-18
  • 2021-07-03
  • 1970-01-01
相关资源
最近更新 更多