问题
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