MongoDb 和 Golang - $group 和 $match

我试图在 $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},

    ])

我错过了什么吗?


红糖糍粑
浏览 80回答 1
1回答

慕容森

它应该有效,确保您所有的字段都是有效日期或使用$toDatedb.collection.aggregate([  {    $group: {      _id: "$batchid",      btime: {        $max: "$createdAt"      },      doc: {        $push: "$$ROOT"      }    }  },  {    $match: {      btime: {        $gt: "2021-07-01T11:23:25.184Z"      }    }  }])mongo游乐场
打开App,查看更多内容
随时随地看视频慕课网APP