How to run mongo command with mongo-go-driver?

不打扰是莪最后的温柔 提交于 2021-01-27 19:11:04

问题


Hi there :) I'm working on a golang app linked to mongo DB (I use the official driver: mongo-go) and here's my problem,I want to execute this function

db.rmTickets.find().forEach(function(doc) {
    doc.created=new Date(doc.created)
    doc.updated=new Date(doc.updated)
    doc.deadline=new Date(doc.deadline)
    doc.dateEstimationDelivery=new Date(doc.dateEstimationDelivery)
    doc.dateTransmitDemand=new Date(doc.dateTransmitDemand)
    doc.dateTransmitQuotation=new Date(doc.dateTransmitQuotation)
    doc.dateValidationQuotation=new Date(doc.dateValidationQuotation)
    doc.dateDeliveryCS=new Date(doc.dateDeliveryCS)
    db.rmTickets.save(doc)
})

I see on godoc that a Database.RunCommand() exists but I'm not sure about how to use it. If someone can help :) Thanks


回答1:


RunCommand is to execute a mongo command. What you intend to do are to find all documents of a collection, make changes, and then replace them. You need Find(), cursor, and ReplaceOne(). Here is a similar code snippet.

if cur, err = collection.Find(ctx, bson.M{"hometown": bson.M{"$exists": 1}}); err != nil {
    t.Fatal(err)
}
var doc bson.M
for cur.Next(ctx) {
    cur.Decode(&doc)
    doc["updated"] = time.Now()
    if result, err = collection.ReplaceOne(ctx, bson.M{"_id": doc["_id"]}, doc); err != nil {
        t.Fatal(err)
    }
    if result.MatchedCount != 1 || result.ModifiedCount != 1 {
        t.Fatal("replace failed, expected 1 but got", result.MatchedCount)
    }
}

I have a full example TestReplaceLoop()



来源:https://stackoverflow.com/questions/53885925/how-to-run-mongo-command-with-mongo-go-driver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!