Hi there :)我正在开发一个链接到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(),但我不确定如何使用它。如果有人能帮忙:)谢谢
发布于 2019-01-05 05:52:46
RunCommand将执行一个mongo命令。您要做的是查找集合中的所有文档,进行更改,然后替换它们。您需要Find()、cursor和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()
https://stackoverflow.com/questions/53885925
复制相似问题