【问题标题】:Mongodb :- merging object ifNull then return data if presentMongodb :- 合并对象 ifNull 然后返回数据(如果存在)
【发布时间】:2023-02-02 10:50:08
【问题描述】:

this Question 的扩展,接受的答案有效,但有些事情我不明白。

一切正常,但还有一件事是如果 array1 即 shiftListData 没有任何日期的任何数据例如让我们取 25th Jan 2023 但 array2 即 attendances25th Jan 2023 的数据那么它不会合并既反对又不返回任何内容,即即使数据存在于 array2 上,它也会跳过该日期

【问题讨论】:

    标签: mongodb mongoose mongodb-query aggregation-framework


    【解决方案1】:

    根据我的解释,问题更关心的是将信息从attendances“修补”到shiftListData。虽然您的担忧是正确且可以理解的,但我想说这种情况可能没有那么有意义,因为在这种情况下它不会产生有意义的合并shiftListData

    不过,以上只是我个人的解读。我们仍然可以通过应用与原始解决方案相同的想法来解决您的问题。我们只需要恢复合并顺序来创建另一个合并结果。使用 $setUnion 将它们连接在一起以创建最终的合并列表。

    db.collection.aggregate([
      {
        $set: {
          shiftListData1: {
            $map: {
              input: "$shiftListData",
              as: "shift",
              in: {
                $mergeObjects: [
                  "$$shift",
                  {
                    $ifNull: [
                      {
                        $first: {
                          $filter: {
                            input: "$attendances",
                            cond: {
                              $eq: [
                                "$$this.Date",
                                "$$shift.date"
                              ]
                            }
                          }
                        }
                      },
                      {}
                    ]
                  }
                ]
              }
            }
          },
          shiftListData2: {
            $map: {
              input: "$attendances",
              as: "a",
              in: {
                $mergeObjects: [
                  {
                    $ifNull: [
                      {
                        $first: {
                          $filter: {
                            input: "$shiftListData",
                            cond: {
                              $eq: [
                                "$$this.date",
                                "$$a.Date"
                              ]
                            }
                          }
                        }
                      },
                      {}
                    ]
                  },
                  "$$a"
                ]
              }
            }
          },
          attendances: "$$REMOVE"
        }
      },
      {
        "$project": {
          shiftListData: {
            $setUnion: [
              "$shiftListData1",
              "$shiftListData2"
            ]
          }
        }
      }
    ])
    

    Mongo Playground

    【讨论】:

      猜你喜欢
      • 2015-11-24
      • 2019-09-28
      • 1970-01-01
      • 1970-01-01
      • 2019-09-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-10
      • 2021-05-15
      相关资源
      最近更新 更多