如何使用mongo-go-driver运行mongo命令? [英] How to run mongo command with mongo-go-driver?

查看:151
本文介绍了如何使用mongo-go-driver运行mongo命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好:)我正在开发一个链接到mongo DB的golang应用程序(我使用的是官方驱动程序: mongo-go ),这是我的问题,我要执行此功能

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

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

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

推荐答案

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

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

我有完整的示例 TestReplaceLoop()

这篇关于如何使用mongo-go-driver运行mongo命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆