mongodb版本2.6.5,mongodb-c-driver驱动用什么版本 1C

之前用的是1.1.10,可以用最新的版本1.6.2吗。mongodb 2.6.5有没有对应最佳版本的c驱动


mongodb都升到3.4了。2.6.5太老了,它的驱动肯定也只能用老版本,新版本应该是匹配mongodb 3.4等的

Csdn user default icon

<div class="post-text" itemprop="text"> <p>How to import official mongoDB driver package in Go?</p> <p>I am following the official Go-mongoDB-driver package instruction (<a href="" rel="nofollow noreferrer"></a>). I have installed the mongoDB package using this:</p> <pre><code>go get </code></pre> <p>but I just can't import the package</p> <p>I am doing a very simple snippet in my <code>main.go</code></p> <pre><code>package main import " func main() { } </code></pre> <p>This gives me:</p> <pre><code>main.go:8:8: code in directory $GOPATH/src/ expects import "" </code></pre> <p>When I tried to import <code></code>, It gives me this:</p> <pre><code>main.go:10:8: cannot find package "" in any of: /usr/local/go/src/ (from $GOROOT) $GOPATH/src/ (from $GOPATH) </code></pre> <p>Kindly help, quite new in Go and not sure where to look since I don't find people having this issue a lot.</p> </div>

您如何使用官方的mongo-go-driver连接到MongoDB Atlas [重复]

<div class="post-text" itemprop="text"> <div class="question-status question-originals-of-duplicate"> <p>This question already has an answer here:</p> <ul> <li> <a href="/questions/52052311/how-to-use-new-url-from-mongodb-3-6-to-connect-from-golang" dir="ltr">How to use new URL from mongodb 3.6 to connect from golang</a> <span class="question-originals-answer-count"> 1 answer </span> </li> </ul> </div> <p>I'm looking at the <a href="" rel="nofollow noreferrer">tutorial</a> offered in conjunction with the release of the official <a href="" rel="nofollow noreferrer">mongo-go-driver</a> and the connection example uses a MongoDB server on <code>localhost</code></p> <pre><code>// Set client options clientOptions := options.Client().ApplyURI("mongodb://localhost:27017") </code></pre> <p>However, the new hosted MongoDB service <a href="" rel="nofollow noreferrer">Atlas</a> requires username and password to login. The connection string takes the format </p> <pre><code>mongodb://[username:password@]host1[/[database][?options]] </code></pre> <p>but there is no Golang example in the <a href="" rel="nofollow noreferrer">driver examples for Atlas</a>.</p> <p>So I'm wondering, what is the best way to log into Atlas without hard coding a password into a source file that will be posted on Github?</p> </div>

Golang MongoDB导入问题

<div class="post-text" itemprop="text"> <p>Facing issue importing golang mongodb driver. </p> <pre><code> go get -u go get -u </code></pre> <p><strong>package unrecognized import path "" (https fetch: Get <a href="" rel="nofollow noreferrer"></a>: dial tcp: lookup no such host)</strong></p> </div>


<div class="post-text" itemprop="text"> <p>I have a little problem with my Go service. I'm new to Go and I just want to dockerize a little service that just connect to a mongodb instance.</p> <p>My code works fine locally. So here is my Dockerfile:</p> <pre><code># build stage FROM golang:alpine AS build-env RUN apk add --no-cache git ADD . . RUN go get -v -u RUN go build -o mongotest # final stage FROM alpine WORKDIR /app COPY --from=build-env ./go/mongotest . RUN apk update &amp;&amp; apk add ca-certificates &amp;&amp; rm -rf /var/cache/apk/* EXPOSE 8000 CMD ["./mongotest"] </code></pre> <p>When I build it, I have this error message :</p> <pre class="lang-none prettyprint-override"><code>Step 6/18 : RUN go get -v -u ---&gt; Running in 4c45c601800d Fetching Parsing meta tags from (status code 200) get "": found meta tag get.metaImport{Prefix:"", VCS:"git", RepoRoot:""} at (download) package no Go files in /go/src/ The command '/bin/sh -c go get -v -u' returned a non-zero code: 1 </code></pre> <p><code>no Go files in /go/src</code> ... ok, what can I do with that?</p> <p>The strange thing is that if I replace </p> <p><code>RUN go get -d -u</code></p> <p>by </p> <p><code>RUN go get -d -u</code></p> <p>it works!</p> <p>Is there a problem with mongo driver repo?</p> </div>


<div class="post-text" itemprop="text"> <p>I can't get the official go mongo driver to successfully return objects that are queried via a regex query.</p> <p>I already know how to do it via the mongo shell and get my expected results. With this example i get all entries that contain "he" in their 'text' field:</p> <pre><code>db.getCollection('test').find({"text": /he/}) </code></pre> <p>same with this one:</p> <pre><code>db.getCollection('test').find({"text": {$regex: /he/, $options: ''}}) </code></pre> <p>This is my current code that doesn't work:</p> <pre><code>package main import ( "context" "fmt" "time" "" "" "" "" ) func main() { ctx, cancel := context.WithTimeout(context.Background(), time.Duration(5*time.Second)) defer cancel() client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017")) if err != nil { fmt.Println(err) return } err = client.Connect(ctx) if err != nil { fmt.Println(err) return } db := client.Database("test") coll := db.Collection("test") filter := bson.D{{"text", primitive.Regex{Pattern: "/he/", Options: ""}}} ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second) defer cancel() cur, err := coll.Find(ctx, filter) if err != nil { fmt.Println(err) return } i := 0 for cur.Next(ctx) { i = i + 1 } fmt.Println("Found", i, "elements") } </code></pre> <p>Per <a href="" rel="nofollow noreferrer">example</a> in the official mongo-go-driver repository, this should work.</p> <p>My current entries in the collection just contain 2 fields, the id field and an extra text field. I currently have 3 entries. that look like this:</p> <pre><code>{ "_id" : ObjectId("5c9cc7e9950198ceeefecbdd"), "text" : "hello world" }, { "_id" : ObjectId("5c9cc7f6950198ceeefecbec"), "text" : "hello" }, { "_id" : ObjectId("5c9cc804950198ceeefecbfa"), "text" : "test world" } </code></pre> <p>My expected results with the code from above, should be the first 2 entries. Instead i get an empty cursor back. </p> <p>Does anybode know, what i am doing wrong? Thanks for your help.</p> </div>

如何使用mongodb / mongo-go-driver执行有效的分页

<div class="post-text" itemprop="text"> <p>I read in the following article that it is more efficient to use the natural ordering of <code>_id</code> to perform paging because skip always starts from the beginning from the collection</p> <p><a href="" rel="nofollow noreferrer"></a> </p> <pre><code>// Page 1 db.students.find().limit(10) // Page 2 last_id = ... # logic to get last_id db.students.find({'_id': {'$gt': last_id}}).limit(10) </code></pre> <p>But I have no idea how to perform the above using the <code>mongodb/mongo-go-driver</code>.</p> </div>


<div class="post-text" itemprop="text"> <p>I am using the package: <code>""</code></p> <p>I am trying to use the following as specified in the <a href="" rel="nofollow noreferrer">documentation</a>:</p> <pre><code>mongoContext, _ := context.WithTimeout(context.Background(), 10*time.Second) mongoClient, _ := mongo.Connect(mongoContext, "mongodb://localhost:27017") </code></pre> <p>However on the second line I get the error:</p> <pre><code>cannot use "mongodb://localhost:27017" (type string) as type *options.ClientOptions in argument to mongo.Connect </code></pre> <p>It seems the documentation doesn't match the implementation. Has anyone been successful?</p> <p><strong>The documentation states:</strong></p> <pre><code>//To do this in a single step, you can use the Connect function: ctx, _ := context.WithTimeout(context.Background(), 10*time.Second) client, err := mongo.Connect(ctx, "mongodb://localhost:27017") </code></pre> </div>

使用mongodb go驱动程序将文档解码为具有自定义类型字段的结构

<div class="post-text" itemprop="text"> <p>I'm a beginner in both go and mongodb. I try to decode a <code>DocumentResult</code> into a struct using bson tags, and it does not work for a custom type wrapping a string. Can it be done without changing the field's type to a string?</p> <pre><code> import ( "context" "" ) type MyDoc struct { SomeInt int `bson:"some_int"` SomeString string `bson:"some_string,omitempty"` CustomType MyType `bson:"custom_type,omitempty"` } type MyType string const myType MyType = "ABCD" func main() { //Connect to db client, _ := mongo.Connect(context.Background(), "mongodb://localhost:27017", nil) db := client.Database("example_db") collection := db.Collection("col") //Insert document docToInsert := MyDoc{42, "The Answer", myType} collection.InsertOne(nil, docToInsert) //Retrieve document filterDoc := MyDoc{SomeInt: 42} resultDoc := &amp;MyDoc{} result := collection.FindOne(nil, filterDoc) result.Decode(resultDoc) println(resultDoc.SomeInt, resultDoc.SomeString, resultDoc.CustomType) </code></pre> <blockquote> <p>PRINTED RESULT: "42 The Answer" //"ABCD" is missing</p> </blockquote> <p>Thanks in advance</p> </div>

无法在我的项目中安装“jenssegers / mongodb”

<div class="post-text" itemprop="text"> <p>I'm cloned my project from git repository and tried to install packages (composer install), but I get an error:</p> <pre><code>Problem 1 - jenssegers/mongodb v3.5.0 requires mongodb/mongodb ^1.0.0 -&gt; satisfiable by mongodb/mongodb[1.0.0, 1.0.0-alpha1, 1.0.0-beta1, 1.0.0-beta2, 1.0.1, 1.0.2, 1.0.3, 1.0.4, 1.0.5, 1.1.0, 1.1.0-alpha1, 1.1.1, 1.1.2, 1.2.0, 1.2.0-alpha1, 1.3.0, 1.3.1, 1.3.2, 1.4.0, 1.4.1, 1.4.2, 1.4.3, 1.5.x-dev, v1.0.x-dev, v1.1.x-dev, v1.2.x-dev, v1.3.x-dev, v1.4.x-dev]. - mongodb/mongodb v1.4.x-dev requires ext-mongodb ^1.5.0 -&gt; the requested PHP extension mongodb is missing from your system. </code></pre> <p>...</p> <pre><code>To enable extensions, verify that they are enabled in your .ini files: - /usr/local/etc/php/7.3/php.ini - /usr/local/etc/php/7.3/conf.d/ext-opcache.ini - /usr/local/etc/php/7.3/conf.d/php-memory-limits.ini You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode. Installation failed, reverting ./composer.json to its original content. </code></pre> <blockquote> <p>I added "" to "php.ini", but it didn't help. What I need to do for fix this?</p> </blockquote> <p><em>MacOS Mojave, Homebrew, Valet, php@7.3, lumen@5.6</em></p> </div>


本人学生小白,想配置mongodb-c-driver,在官网上下了mongo-c-driver-1.1.6和cmake,按照教程用cmake先生成libbson的vs工程文件,然后用VS2012编译,结果报错了... 错误如下: 错误 52 error MSB3073: 命令“setlocal "E:\Program Files (x86)\CMake\bin\cmake.exe" -DBUILD_TYPE=Debug -P cmake_install.cmake if %errorlevel% neq 0 goto :cmEnd :cmEnd endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone :cmErrorLevel exit /b %1 :cmDone if %errorlevel% neq 0 goto :VCEnd :VCEnd”已退出,代码为 1。 C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V110\Microsoft.CppCommon.targets 134 我的环境是window 64位操作系统,VS2012 第一次提问,跪谢各位大神!

windows 上 MongoDB的C++driver编译报错

![图片说明]( 要把MongoDB c++driver编译成vc程序使用的库,scons编译的时候报错,错误文件居然是MongoDB官网下载的驱动里的文件 SConstruct, 求解。 版本: mongo-cxx-driver-legacy-1.1.2 boost\_1\_66\_0 python 3.6 scons 3.0


<div class="post-text" itemprop="text"> <p>I'm using mongo-go-driver, parallel connect several ports to check whether the port is listened by mongodb </p> <p>go version 1.12.3 mongo-go-driver v1.0</p> <pre class="lang-golang prettyprint-override"><code>type BaseServerStatus struct { Host string `bson:"host"` Version string `bson:"version"` Process string `bson:"process"` Pid int64 `bson:"pid"` Uptime int64 `bson:"uptime"` UptimeMillis int64 `bson:"uptimeMillis"` UptimeEstimate int64 `bson:"uptimeEstimate"` LocalTime time.Time `bson:"localTime"` } func GetBaseServerStatus(ip, port string) (srvStatus *BaseServerStatus, err error) { opts := options.Client() opts.SetDirect(true) opts.SetServerSelectionTimeout(1 * time.Second) opts.SetConnectTimeout(2 * time.Second) opts.SetSocketTimeout(2 * time.Second) opts.SetMaxConnIdleTime(1 * time.Second) opts.SetMaxPoolSize(1) url := fmt.Sprintf("mongodb://%s:%s/admin", ip, port) opts.ApplyURI(url) ctx, _ := context.WithTimeout(context.Background(), 2*time.Second) conn, err := mongo.Connect(ctx, opts) if err != nil { fmt.Printf("new %s:%s mongo connection error: %v ", ip, port, err) return } defer conn.Disconnect(ctx) err = conn.Ping(ctx, nil) if err != nil { fmt.Printf("ping %s:%s ping error: %v ", ip, port, err) return } sr := conn.Database("admin").RunCommand(ctx, bson.D{{"serverStatus", 1}}) if sr.Err() != nil { fmt.Printf("get %s:%s server status error: %v ", ip, port, sr.Err()) return } srvStatus = new(BaseServerStatus) err = sr.Decode(srvStatus) return } func main() { var wg sync.WaitGroup //ips := []string{""} ips := []string{"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""} for _, ip := range ips { wg.Add(1) //time.Sleep(3 * time.Second) go func(addr string) { fmt.Printf("start to probe port %s ", addr) GetBaseServerStatus(strings.Split(addr, ":")[0], strings.Split(addr, ":")[1]) wg.Done() }(ip) } wg.Wait() fmt.Println("scan end") time.Sleep(20 * time.Second) } </code></pre> <p>however, run this code ,it consume 26GB memory I use pprof to diagnose, see below</p> <p>Showing top 10 nodes out of 15 flat flat% sum% cum cum% 26.29GB 96.86% 96.86% 26.29GB 96.86%*connection).ReadWireMessage</p> </div>


<div class="post-text" itemprop="text"> <p>I want to convert bson in <a href="" rel="nofollow noreferrer">mongo-go-driver</a> to json effectively.</p> <p>I should take care to handle <code>NaN</code>, because <code>json.Marshal</code> fail if <code>NaN</code> exists in data.</p> <p>For instance, I want to convert below bson data to json.</p> <pre class="lang-golang prettyprint-override"><code>b, _ := bson.Marshal(bson.M{"a": []interface{}{math.NaN(), 0, 1}}) // How to convert b to json? </code></pre> <p>The below fails.</p> <pre class="lang-golang prettyprint-override"><code>// decode var decodedBson bson.M bson.Unmarshal(b, &amp;decodedBson) _, err := json.Marshal(decodedBson) if err != nil { panic(err) // it will be invoked // panic: json: unsupported value: NaN } </code></pre> </div>

mongodb 为什么高版本api写入比低版本api写入效率低

* 同一台服务器上,非集群单机测试,插入2个共1.1GB数据 * 写入数据用的java高版本api是3.8,低版本api是2.4 * mongo2.4不支持高版本api --- ![图片说明]( --- 用低版本2.4api的collection.insert(listdbo);每提交10万行耗时4s 用高版本3.8api的collection.insertMany(listdbo);每提交10万行耗时7s 低版本api写入mongodb2.4和mongodb4.0耗时基本一样 --- # **为什么高版本api写入mongodb4.0耗时会比较长????**

mongodb-go-driver / bson结构转换为bson.Document编码

<div class="post-text" itemprop="text"> <p>I'm working with <a href="" rel="nofollow noreferrer"></a> and currently trying to implement a partial update of such struct</p> <pre><code>type NoteUpdate struct { ID string `json:"id,omitempty" bson:"_id,omitempty"` Title string `json:"title" bson:"title,omitempty"` Content string `json:"content" bson:"content,omitempty"` ChangedAt int64 `json:"changed_at" bson:"changed_at"` } </code></pre> <p>For instance, if I have</p> <pre><code>noteUpdate := NoteUpdate{ Title: "New Title" } </code></pre> <p>Then I expect that the only "title" field in the stored document will be changed.</p> <p>I need to write something like</p> <pre><code>collection.FindOneAndUpdate(context.Background(), bson.NewDocument(bson.EC.String("_id", noteUpdate.ID)), // I need to encode non-empty fields here bson.NewDocument(bson.EC.SubDocument("$set", bson.NewDocument(...))) ) </code></pre> <p>The problem is that I don't want to manually encode each non-empty field with <code>bson.EC.String(...)</code> or <code>bson.EC.Int64(...)</code>. I tried to use <code>bson.EC.InterfaceErr(...)</code> but got an error </p> <blockquote> <p>Cannot create element for type *models.NoteUpdate, try using bsoncodec.ConstructElementErr</p> </blockquote> <p>Unfortunately, there is no such function in bsoncodec. The only way I found is to create wrapper </p> <pre><code>type SetWrapper struct { Set interface{} `bson:"$set,omitempty"` } </code></pre> <p>And use it like</p> <pre><code>partialUpdate := &amp;NoteUpdate{ ID: "some-note-id", Title: "Some new title", } updateParam := SetWrapper{Set: partialUpdate} collection.FindOneAndUpdate( context.Background(), bson.NewDocument(bson.EC.String("_id", noteUpdate.ID)), updateParam, ) </code></pre> <p>It works, but is it possible to achieve the same with bson/bsoncodec document builders ?</p> <p>UPD. The full context of my question: I wrote the REST endpoint for <strong>partially</strong> updating "Note" documents(stored in MongoDB). Code that I have now:</p> <pre><code>var noteUpdate models.NoteUpdate ctx.BindJSON(&amp;noteUpdate) //omit validation and errors handling updateParams := services.SetWrapper{Set: noteUpdate} res := collection.FindOneAndUpdate( context.Background(), bson.NewDocument(bson.EC.String("_id", noteUpdate.ID)), updateParams, findopt.OptReturnDocument(option.After), ) </code></pre> <p>Code that I want to have</p> <pre><code>var noteUpdate models.NoteUpdate ctx.BindJSON(&amp;noteUpdate) //omit validation and errors handling res := collection.FindOneAndUpdate( context.Background(), bson.NewDocument(bson.EC.String("_id", noteUpdate.ID)), bson.NewDocument( //bsoncodec.ConstructElement doesn't exists bsoncodec.ConstructElement("$set", &amp;noteUpdate)), ), findopt.OptReturnDocument(option.After), ) </code></pre> <p>Code that I <strong>don't</strong> want to have</p> <pre><code>var noteUpdate models.NoteUpdate ctx.BindJSON(&amp;noteUpdate) //omit validation and errors handling bsonNote := bson.NewDocument() if noteUpdate.Title != "" { bsonNote.Append(bson.EC.String("title", noteUpdate.Title)) } if noteUpdate.Content != "" { bsonNote.Append(bson.EC.String("content", noteUpdate.Content)) } //..setting the rest of the fields... res := collection.FindOneAndUpdate( context.Background(), bson.NewDocument(bson.EC.String("_id", noteUpdate.ID)), bson.NewDocument(bson.EC.SubDocument("$set", bsonNote)), findopt.OptReturnDocument(option.After), ) </code></pre> <p>So, the precise question is - is there any way to build *bson.Document dynamically based on <code>bson</code> tags(without predefined wrappers like my SetWrapper)? </p> </div>

使用struct&mongodb / mongo-go-driver更新/替换mongodb文档

<div class="post-text" itemprop="text"> <p>I am trying to update/replace a mongodb document using a struct but i keep on getting <code>err: update document must contain key beginning with '$'</code></p> <pre><code>collection := r.client.Database(database).Collection(greetingCollection) payment.MongoID = objectid.New() filter := bson.NewDocument(bson.EC.String("id", payment.ID)) _, err := collection.UpdateOne(ctx, filter, payment) return err </code></pre> </div>

官方mongo-go-driver的UpdateOne中$ set的bson语法是什么

<div class="post-text" itemprop="text"> <p>I am trying to get some familiarity with the official <a href="" rel="nofollow noreferrer">mongo-go-driver</a> and ran into an hour-long delay trying to figure out the right syntax for <code>UpdateOne</code>. </p> <p>My simplest full example follows (NOTE: in order to use this code you will need to substitute in your own user and server names as well as export the login password to the environment as MONGO_PW):</p> <pre class="lang-golang prettyprint-override"><code>package main import ( "context" "fmt" "os" "" "" "" "" ) type DB struct { User string Server string Database string Collection string Client *mongo.Client Ctx context.Context } var db = DB{ User: &lt;username&gt;, Server: &lt;server_IP&gt;, Database: "test", Collection: "movies", Ctx: context.TODO(), } type Movie struct { ID primitive.ObjectID `bson:"_id" json:"id"` Name string `bson:"name" json:"name"` Description string `bson:"description" json:"description"` } func main() { if err := db.Connect(); err != nil { fmt.Println("error: unable to connect") os.Exit(1) } fmt.Println("connected") // The code assumes the original entry for dunkirk is the following // {"Name":"dunkirk", "Description":"a world war 2 movie"} updatedMovie := Movie{ Name: "dunkirk", Description: "movie about the british evacuation in WWII", } res, err := db.UpdateByName(updatedMovie) if err != nil { fmt.Println("error updating movie:", err) os.Exit(1) } if res.MatchedCount &lt; 1 { fmt.Println("error: update did not match any documents") os.Exit(1) } } // UpdateByName changes the description for a movie identified by its name func (db *DB) UpdateByName(movie Movie) (*mongo.UpdateResult, error) { filter := bson.D{{"name", movie.Name}} res, err := db.Client.Database(db.Database).Collection(db.Collection).UpdateOne( db.Ctx, filter, movie, ) if err != nil { return nil, err } return res, nil } // Connect assumes that the database password is stored in the // environment variable MONGO_PW func (db *DB) Connect() error { pw, ok := os.LookupEnv("MONGO_PW") if !ok { fmt.Println("error: unable to find MONGO_PW in the environment") os.Exit(1) } mongoURI := fmt.Sprintf("mongodb+srv://%s:%s@%s", db.User, pw, db.Server) // Set client options and verify connection clientOptions := options.Client().ApplyURI(mongoURI) client, err := mongo.Connect(db.Ctx, clientOptions) if err != nil { return err } err = client.Ping(db.Ctx, nil) if err != nil { return err } db.Client = client return nil } </code></pre> <p>The function signature for <code>UpdateOne</code> from the package docs is:</p> <pre class="lang-golang prettyprint-override"><code>func (coll *Collection) UpdateOne(ctx context.Context, filter interface{}, update interface{}, opts ...*options.UpdateOptions) (*UpdateResult, error) </code></pre> <p>So I am clearly making some sort of mistake in creating the <code>update interface{}</code> argument to the function because I am presented with this error</p> <pre class="lang-none prettyprint-override"><code>error updating movie: update document must contain key beginning with '$' </code></pre> <p>The most popular answer <a href="">here</a> shows that I need to use a document sort of like this </p> <pre><code>{ $set: {"Name" : "The Matrix", "Decription" "Neo and Trinity kick butt" } } </code></pre> <p>but taken verbatim this will not compile in the mongo-go-driver.</p> <p>I think I need some form of a bson document to comply with the Go syntax. What is the best and/or most efficient syntax to create this bson document for the <code>update</code>?</p> </div>


<div class="post-text" itemprop="text"> <p>So I am trying to use <a href="" rel="nofollow noreferrer"></a> to connect to a mongo database in golang.</p> <p>Here is my connection handler: </p> <pre><code>var DB *mongo.Database func CreateConnectionHandler()(*mongo.Database, error){ fmt.Println("inside createConnection in database package") godotenv.Load() fmt.Println("in CreateConnectionHandler and SERVER_CONFIG: ") fmt.Println(os.Getenv("SERVER_CONFIG")) uri:="" if os.Getenv("SERVER_CONFIG")=="kubernetes"{ fmt.Println("inside kubernetes db config") uri = "mongodb://patientplatypus:SUPERSECRETPASSDOOT@ mongo-release-mongodb.default.svc.cluster.local:27017/ platypusNEST?authMechanism=SCRAM-SHA-1" }else if os.Getenv("SERVER_CONFIG")=="compose"{ fmt.Println("inside compose db config") uri = "mongodb://datastore:27017" } ctx, _ := context.WithTimeout(context.Background(), 10*time.Second) client, err := mongo.Connect(ctx, uri) if err != nil { return nil, fmt.Errorf("mongo client couldn't connect: %v", err) } DB := client.Database("platypusNEST") return DB, nil } </code></pre> <p>And the error I am getting: </p> <pre><code>api | database/connection.go:29:30: cannot use uri (type string) as type *options.ClientOptions in argument to mongo.Connect </code></pre> <p>So I tried replacing <code>uri</code> with the connection string like this: </p> <pre><code>client, err := mongo.Connect(ctx, "mongodb://datastore:27017") </code></pre> <p>But I still got the error.</p> <p>Compare this with what is in the documentation: </p> <blockquote> <pre><code>ctx, _ := context.WithTimeout(context.Background(), 10*time.Second) client, err := mongo.Connect(ctx, "mongodb://localhost:27017") </code></pre> </blockquote> <p>And it is exactly the same! I'm really not sure why there is this error. Any ideas?</p> </div>

使用MongoDB Atlas时,mongo-go-driver失败,服务器选择超时

<div class="post-text" itemprop="text"> <p>Go Version: 1.12.5</p> <p>I have this code which uses the node.js mongo driver</p> <pre><code>const MongoClient = require('mongodb').MongoClient; const uri = process.env.MONGO_HOST + "dbname?retryWrites=true"; const client = new MongoClient(uri, { useNewUrlParser: true }); client.connect(async (err) =&gt; { if (err) { throw err } const collection = client.db("dbname").collection("collectionName"); const cursor = collection.find() await cursor.forEach(console.log) // perform actions on the collection object client.close(); }); </code></pre> <p>Which works fine.</p> <p>Using the <code>mongo-go-driver</code>, I do:</p> <pre><code>client, err := mongo.NewClient(options.Client().ApplyURI(os.Getenv("MONGO_HOST") + "dbname?retryWrites=true") if err != nil { panic(err) } ctx, _ := context.WithTimeout(context.Background(), 10*time.Second) err = client.Connect(ctx) if err != nil { panic(err) } database := client.Database("dbname") collection := database.Collection("collectionName") res, err := collection.Find(context.Background(), bson.M{}, &amp;options.FindOptions{ Sort: bson.M{ "priority": -1, }, }) if err != nil { panic(err) } results := make([]structs.ResponseType, 0) err = res.All(context.Background(), &amp;results) if err != nil { panic(err) } </code></pre> <p>But this panics with:</p> <pre><code>panic: server selection error: server selection timeout current topology: Type: ReplicaSetNoPrimary </code></pre> <p>I am not running this inside a container/docker.</p> </div>


今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...



和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...


“亚马逊丛林里的蝴蝶扇动几下翅膀就可能引起两周后美国德州的一次飓风……” 这句人人皆知的话最初用来描述非线性系统中微小参数的变化所引起的系统极大变化。 而在更长的时间尺度内,我们所生活的这个世界就是这样一个异常复杂的非线性系统…… 水泥、穹顶、透视——关于时间与技艺的蝴蝶效应 公元前3000年,古埃及人将尼罗河中挖出的泥浆与纳特龙盐湖中的矿物盐混合,再掺入煅烧石灰石制成的石灰,由此得来了人...






提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...




私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...


今天给你们讲述一个外包程序员的幸福生活。男主是Z哥,不是在外包公司上班的那种,是一名自由职业者,接外包项目自己干。接下来讲的都是真人真事。 先给大家介绍一下男主,Z哥,老程序员,是我十多年前的老同事,技术大牛,当过CTO,也创过业。因为我俩都爱好喝酒、踢球,再加上住的距离不算远,所以一直也断断续续的联系着,我对Z哥的状况也有大概了解。 Z哥几年前创业失败,后来他开始干起了外包,利用自己的技术能...


本文介绍一些C++的两个新特性,它们虽然微小,但对你的编程十分重要 一、Template表达式内的空格 C++11标准之前建议在“在两个template表达式的闭符之间放一个空格”的要求已经过时了 例如: vector&lt;list&lt;int&gt; &gt;; //C++11之前 vector&lt;list&lt;int&gt;&gt;; //C++11 二、nullptr ...


场景 日常开发,if-else语句写的不少吧??当逻辑分支非常多的时候,if-else套了一层又一层,虽然业务功能倒是实现了,但是看起来是真的很不优雅,尤其是对于我这种有强迫症的程序"猿",看到这么多if-else,脑袋瓜子就嗡嗡的,总想着解锁新姿势:干掉过多的if-else!!!本文将介绍三板斧手段: 优先判断条件,条件不满足的,逻辑及时中断返回; 采用策略模式+工厂模式; 结合注解,锦...



离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...


不知道是不是只有我这样子,还是你们也有过类似的经历。 上学的时候总有很多光辉历史,学年名列前茅,或者单科目大佬,但是虽然慢慢地长大了,你开始懈怠了,开始废掉了。。。 什么?你说不知道具体的情况是怎么样的? 我来告诉你: 你常常潜意识里或者心理觉得,自己真正的生活或者奋斗还没有开始。总是幻想着自己还拥有大把时间,还有无限的可能,自己还能逆风翻盘,只不是自己还没开始罢了,自己以后肯定会变得特别厉害...




当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...


HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...



面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?







已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...



《Oracle Java SE编程自学与面试指南》最佳学习路线图(2020最新版)





作者 | 伍杏玲出品 | CSDN(ID:CSDNnews)格子衬衫、常掉发、双肩包、修电脑、加班多……这些似乎成了大众给程序员的固定标签。近几年流行的“跨界风”开始刷新人们对程序员的...






不怕告诉你,我自从喜欢上了这12个UP主,哔哩哔哩成为了我手机上最耗电的软件,几乎每天都会看,可是吧,看的越多,我就越觉得自己是个废柴,唉,老天不公啊,不信你看看…… 间接性踌躇满志,持续性混吃等死,都是因为你们……但是,自己的学习力在慢慢变强,这是不容忽视的,推荐给你们! 都说B站是个宝,可是有人不会挖啊,没事,今天咱挖好的送你一箩筐,首先啊,我在B站上最喜欢看这个家伙的视频了,为啥 ,咱撇...