登录
首页 >  Golang >  Go问答

在Go中永久更改未保存的Mongodb聚合

来源:stackoverflow

时间:2024-02-13 22:09:21 276浏览 收藏

golang学习网今天将给大家带来《在Go中永久更改未保存的Mongodb聚合》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习Golang或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!

问题内容

我正在运行聚合来删除过时的文档,但这些更改实际上不会影响数据库。该查询会忽略已经过期的文档,因此结果数应该在每次查询运行后发生变化,但事实并非如此。

func checkshipmentexpirydates(c *mongo.client) (int, error) {
    numberofexpiredshipments := 0
    coll := c.database(os.getenv("database")).collection("shipments")
    update := bson.m{"$set": bson.m{"status": "expired", "updated_at": time.now()}}
    pipeline := []bson.m{
        {"$lookup": bson.m{
            "from": "shipment_quotes",
            "let":  bson.m{"shipmentid": "$_id"},
            "pipeline": []bson.m{
                {"$match": bson.m{"$expr": bson.m{"$and": []bson.m{{"$eq": []string{"$shipment_id", "$$shipmentid"}}, {"$eq": []string{"$status", "won"}}}}}},
            },
            "as": "quotes",
        }},
        {"$match": bson.m{"expiration_date": bson.m{"$exists": true}}},
        {"$match": bson.m{"$expr": bson.m{"$and": []bson.m{
            {"$ne": []string{"$status", "expired"}},
            {"$lt": []interface{}{"$expiration_date", time.now()}},
            {"$eq": []interface{}{bson.m{"$size": "$quotes"}, 0}},
            {"expiration_date": bson.m{"$type": 9}},
        }}}},
        update,
    }

    err := c.usesession(context.todo(), func(sessioncontext mongo.sessioncontext) error {
        if err := sessioncontext.starttransaction(); err != nil {
            return err
        }
        cursor, err := coll.aggregate(sessioncontext, pipeline)
        if err != nil {
            _ = sessioncontext.aborttransaction(sessioncontext)
            return err
        }

        var shipments []bson.m
        if err := cursor.all(sessioncontext, &shipments); err != nil {
            _ = sessioncontext.aborttransaction(sessioncontext)
            return err
        }

        fmt.println("~first shipment's status", shipments[0]["shipment_unique_number"], shipments[0]["status"])

        numberofexpiredshipments = len(shipments)

        fmt.println(sessioncontext.committransaction(sessioncontext))
        return nil
    })

    return numberofexpiredshipments, err
}

如您所见,我正在记录第一个结果,并使用指南针实时检查数据库,但更改实际上并未保留。该查询一遍又一遍地运行,返回相同数量的过期货件。

mc, mongoerr := connection.mongoinit()
    if mongoerr != nil {
        panic(mongoerr)
    }
    utils.initdb(mc)
    defer func() {
        if err := mc.disconnect(context.todo()); err != nil {
            panic(err)
        }
    }()

    n := connection.newnotificationcenter()
    sseinit(mc, googleapi, n)
    graphschema, err := schema.injectschema(mutationinit(mc, googleapi), queryinit(mc, googleapi))
    if err != nil {
        panic(err)
    }
    restapiusecase := mutationsrestapiinit(mc, googleapi)
    connection.injectgraphqlhandler(graphschema, n, restapiusecase)

    initincrementstartdate(mc)
    initshipmentexpiredcron(mc)
func initShipmentExpiredCron(mg *mongo.Client) {
    c := cron.New()
    c.AddFunc("*/5 * * * *", func() {
        expiredShipments, err := utils.CheckShipmentExpiryDates(mg)
        if err != nil {
            log.Println("CRON ERROR: An error occured while trying to check the expiry date for each shipment")
            log.Println(err)
        } else {
            // Print how many shipments are expired
            log.Println("CRON SUCCESS: The following number of shipments have expired: ", expiredShipments)
        }
    })
    c.Start()
}

我真的不明白这有什么问题。


正确答案


rickhg12hs 是对的,我还需要使用 $merge。奇怪的是,这使得聚合不返回任何内容,所以现在我不知道已过期的发货数量,但这并不是真正必要的。这是最后的管道

pipeline := []bson.M{{
  "$lookup": bson.M{
    "from": "shipment_quotes",
    "let": bson.M{
      "shipmentID": "$_id"
    },
    "pipeline": []bson.M{{
      "$match": bson.M{
        "$expr": bson.M{
          "$and": []bson.M{{
            "$eq": []string{
              "$shipment_id", "$$shipmentID"
            }}, {
              "$eq": []string{
                "$status", "WON"
              }
            }
          }}
        }
      },
    },
    "as": "quotes",
  }}, {
    "$match": bson.M{
      "expiration_date": bson.M{
        "$exists": true
      }
    }
  }, {
    "$match": bson.M{
      "$expr": bson.M{
        "$and": []bson.M{{
          "$ne": []string{
            "$status", "EXPIRED"
          }
        }, {
          "$lt": []interface{}{
            "$expiration_date", time.Now()
          }
        }, {
          "$eq": []interface{}{
            bson.M{
              "$size": "$quotes"
            }, 0
          }
        }, {
          "expiration_date": bson.M{
            "$type": 9
          }
        },
      }
    }
  }},
  update,
  {
    "$merge": bson.M{
      "into": "shipments",
      "on": "_id"
    }
  },
}

今天关于《在Go中永久更改未保存的Mongodb聚合》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>