mgo

partial update using mgo

巧了我就是萌 提交于 2019-12-04 19:21:59
问题 I have the following problem. I need to convert a structure to map[string]interface{} in order to perform an update in database (using mgo as driver for mongodb). Update For partially updating a document in mongoDB, the (optimal) solution is to convert to a map and delete the unwanted fields. For converting from struct to map please refer to my other post Original Post I receive the data from client side javascript and write in the my struct model. But I don't want to change/update some

Golang/mgo: How can I ask MongoDB to use current time in a field?

蹲街弑〆低调 提交于 2019-12-04 16:10:47
问题 I have this struct that matches the types of a MongoDB collection I'm using: type AppInstance struct { Id bson.ObjectId "_id,omitempty" Url string Priority int LastSeen string } I want the LastSeen field to hold the time of the last interaction with that particular app. So, the app registers itself setting current time (as a string). What I would like is Mongo to dynamically set its own current time into that field when it inserts, just like MySQL's NOW() function would do. I have this helper

Store Uploaded File in MongoDB GridFS Using mgo without Saving to Memory

China☆狼群 提交于 2019-12-04 12:11:05
noob Golang and Sinatra person here. I have hacked a Sinatra app to accept an uploaded file posted from an HTML form and save it to a hosted MongoDB database via GridFS. This seems to work fine. I am writing the same app in Golang using the mgo driver. Functionally it works fine. However in my Golang code, I read the file into memory and then write the file from memory to the MongoDB using mgo. This appears much slower than my equivalent Sinatra app. I get the sense that the interaction between Rack and Sinatra does not execute this "middle" or "interim" step. Here's a snippet of my Go code:

Should I copy session for each operation in mgo?

一个人想着一个人 提交于 2019-12-04 07:27:16
I want to upsert a list of record, so I have two choice, one just use one session, another copy a session for every record. So, as my opinion, first method may slower than the second, but will the first one cause too many session created? 1.use one session func (this *CvStoreServiceImpl) SetCvJobItemMeasureList(accessToken *base_datatype.ServiceAccessToken, versionPolicy string, jobItemList []*cv_common_type.CvJobItemMeasure) (err error) { session := this.session.Clone() defer session.Close() for _, jobItem := range jobItemList { objKey := &orm.ItemIdKey{ VersionName: versionPolicy, //XXX

Prevent runtime panic in bson.ObjectIdHex

十年热恋 提交于 2019-12-04 05:23:26
问题 i'm trying to convert string of objectid to bson ObjectId format with mgo, errCheck := d.C("col").FindId(bson.ObjectIdHex(obid[0])).One(&Result) idk why, but if i give a wrong / invalid input string, my application got runtime panic how i can prevent that ? thank you 回答1: bson.ObjectIdHex() documents that it will panic if you pass an invalid object id: ObjectIdHex returns an ObjectId from the provided hex representation. Calling this function with an invalid hex representation will cause a

How to marshal json string to bson document in golang for writing to MongoDB?

前提是你 提交于 2019-12-04 04:26:32
What I am looking is equivalent of Document.parse() in golang, that allows me create bson from json directly? I do not want to create intermediate golang structs for marshaling TheHippo The gopkg.in/mgo.v2/bson package has a function called UnmarshalJSON which does exactly what you want. The data parameter should hold you JSON string as []byte value. func UnmarshalJSON(data []byte, value interface{}) error UnmarshalJSON unmarshals a JSON value that may hold non-standard syntax as defined in BSON's extended JSON specification. Example: var bdoc interface{} err = bson.UnmarshalJSON([]byte(`{"id"

MongoDB in Go (golang) with mgo: how to use logical operators to query?

喜欢而已 提交于 2019-12-04 03:04:39
I would like to run the following query in golang using mgo in a pipeline. {"key1" : 1, "$or" : [{"key2" : 2}, {"key3" : 2}]} I have looked everywhere, but I cannot find an example like this. I have tried many different combinations, for example: ... pipeline := []bson.M{ bson.M{ "$match" : bson.M{ "key1" : 1, "$or" : bson.M{ "key2" : 2, "key3" : 2}, } ... } which compiles correctly, does not find anything. Any ideas? Thank you in advance Your mongo query can be translated to the following: pipeline := bson.D{ {"key1", 1}, {"$or", []interface{}{ bson.D{{"key2", 2}}, bson.D{{"key3", 2}}, }}, }

Set default date when inserting document with time.Time field

自作多情 提交于 2019-12-04 01:50:33
问题 In mongoose ( node.js ) I can define a model schema with a default Date.now like so: ... type: Date, default: Date.now ... How do I achieve the same without having to insert the time.Time every time I create a document with mgo ? type User struct { CreatedAt time.Time `json:"created_at" bson:"created_at"` // Make this field filled automatically with time.Now() every time a document of this `struct` is inserted } 回答1: In Go you can't define default values for fields, they will always be the

How do you select all records from a mongodb collection in golang using mgo

瘦欲@ 提交于 2019-12-03 22:23:34
In MongoDB doing something like db.mycollection.find() returns all documents in a collection. When working in GoLang using the package labix.org/v2/mgo and I do for example: query := db.C("client").Find(); It complains that it requires input in the form of an interface. All I need to do is retrieve all documents and iterate through them and display each one for now. How do I achieve this effect? All examples I have seen seem to have filters in place. Found a solution: var results []client err := db.C("client").Find(nil).All(&results) if err != nil { // TODO: Do something about the error } else

How to use new URL from mongodb 3.6 to connect from golang

给你一囗甜甜゛ 提交于 2019-12-03 18:13:43
问题 I tried to connect to mongodb Atlas using golang drivers. tlsConfig := &tls.Config{} var mongoURI = "mongodb+srv://admin:password@prefix.mongodb.net:27017/dbname" dialInfo, err := mgo.ParseURL(mongoURI) if err != nil { panic(err) } dialInfo.DialServer = func(addr *mgo.ServerAddr) (net.Conn, error) { conn, err := tls.Dial("tcp", addr.String(), tlsConfig) return conn, err } session, err := mgo.DialWithInfo(dialInfo) if err != nil { println("error") log.Fatal(err) } _ = session c := session.DB(