为了账号安全,请及时绑定邮箱和手机立即绑定

MongoDb 和 Golang - $group 和 $match

MongoDb 和 Golang - $group 和 $match

Go
红糖糍粑 2022-11-23 14:14:38
我试图在 $group 之后 $match 我的数据,但它不起作用。我有工作的数据库。每个作业都有 { id,batchId(几个作业可以属于一个批次),createdAt, finishedAt}。我不明白为什么我得到的结果是空的。我需要获取在 CreatedAtTo 参数之前创建的具有相同 batchId 的作业组。为了保存日期,我使用了 unix 时间戳(所以它是一个整数)我的解决方案:group := bson.M{    "$group": bson.M{        "_id":   "$batchid",        "btime": bson.M{"$max": "$createdAt"},        "doc":   bson.M{"$push": "$$ROOT"},    },}match := bson.M{    "$match": bson.M{        "btime": bson.M{            "$lte": CreatedAtTo},    },}sort := bson.M{"$sort": bson.M{"btime": -1}}limit := bson.M{"$limit": 1}pipeline := []bson.M{group, match, sort, limit}如果我评论 $match 部分它有效,但不是全部。并尝试在robo 3t中表演。它也有效    db.getCollection('jobs').aggregate(    [    {$group:{        "_id":"$batchId",        btime: { $max: "$createdAt"},        bItems: { $push: "$$CURRENT" }    }},    {$match:{"btime": {"$lte": 10}}},    {$sort:{"btime": -1}},    {$limit:1},    ])我错过了什么吗?
查看完整描述

1 回答

?
慕容森

TA贡献1853条经验 获得超18个赞

它应该有效,确保您所有的字段都是有效日期或使用$toDate


db.collection.aggregate([

  {

    $group: {

      _id: "$batchid",

      btime: {

        $max: "$createdAt"

      },

      doc: {

        $push: "$$ROOT"

      }

    }

  },

  {

    $match: {

      btime: {

        $gt: "2021-07-01T11:23:25.184Z"

      }

    }

  }

])

mongo游乐场


查看完整回答
反对 回复 2022-11-23
  • 1 回答
  • 0 关注
  • 76 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信