MongoDB组最小与条款

发布于 2025-02-09 05:16:27 字数 455 浏览 0 评论 0 原文

希望将结果与最低日期汇总在一起,但是最小应该仅适用于状态为真的字段?

鉴于以下数据,$ dateModified的$ min将返回日期为2,但是我希望返回3,因为它是最低的数据,并具有真实状态,

{name: "one", dateModified: "4", status: true},
{name: "one", dateModified: "2", status: false},
{name: "one", dateModified: "3", status: true}

.aggregate([
   $group: {
   _id: "$name",
   date: {$min: "$dateModified" // where status is true},
   total: {$sum: 1}
  }
])

我还需要真实和错误条目的整体计数,因此请应用一个匹配状态:在小组之前是正确的

Looking to aggregate a result with the minimum date however the min should apply only to fields where the status is true?

Given the following data, $min on $dateModified will return date as 2 however I'm looking to return 3 because it is the lowest dateModified with the status of true

{name: "one", dateModified: "4", status: true},
{name: "one", dateModified: "2", status: false},
{name: "one", dateModified: "3", status: true}

.aggregate([
   $group: {
   _id: "$name",
   date: {$min: "$dateModified" // where status is true},
   total: {$sum: 1}
  }
])

I'll also need the overall count of true and false entries so applying a match on status: true before the group may prevent that

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

2025-02-16 05:16:27

为什么不只是添加 $ match 阶段作为第一个使用状态过滤文档的阶段:true

db.collection.aggregate([
  {
    $match: {
      status: true
    }
  },
  {
    $group: {
      _id: "$name",
      date: {
        $min: "$dateModified"
      }
    }
  }
])

示例mongo playground


当您热衷于保持文档的状态:false 状态:false ,然后您可以与 $ cond> $ cond

db.collection.aggregate([
  {
    $group: {
      _id: "$name",
      date: {
        $min: {
          $cond: {
            if: {
              $eq: [
                "$status",
                true
              ]
            },
            then: "$dateModified",
            else: "$REMOVE"
          }
        }
      }
    }
  }
])

示例mongo Playground 2

Why not just add the $match stage as the first stage to filter the documents with status: true only?

db.collection.aggregate([
  {
    $match: {
      status: true
    }
  },
  {
    $group: {
      _id: "$name",
      date: {
        $min: "$dateModified"
      }
    }
  }
])

Sample Mongo Playground


As you are keen to remain the document with status: false, then you can work with $cond and $$REMOVE.

db.collection.aggregate([
  {
    $group: {
      _id: "$name",
      date: {
        $min: {
          $cond: {
            if: {
              $eq: [
                "$status",
                true
              ]
            },
            then: "$dateModified",
            else: "$REMOVE"
          }
        }
      }
    }
  }
])

Sample Mongo Playground 2

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文