如何使用Mongo-Go-Driver运行Mongo命令



嗨:)我正在使用链接到mongo db的Golang应用程序(我使用官方驱动程序:mongo-go),这是我的问题,我想执行此功能

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)
})

我在Godoc上看到Database.RunCommand()存在,但我不确定如何使用它。如果有人可以帮助:)谢谢

RunCommand是执行mongo命令。您打算要做的是找到集合的所有文档,进行更改,然后更换它们。您需要Find(),光标和ReplaceOne()。这是一个类似的代码段。

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)
    }
}

我有一个完整的示例testreplaceloop()

最新更新