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