已经通过mongoc_collection_find()和mongoc_cursor_next()拿到想要的bson_t 类型对象现在想提取该对象中包含的MongoDB唯一标识_id。




 while (mongoc_cursor_more (cursor) && mongoc_cursor_next (cursor, &doc)) {
      str = bson_as_json (doc, NULL);
      printf ("%s\n", str);
      bson_free (str);
半英里外的雨 您的意思是不是对C指针str做键值对"key=value"字符串,然后解析出_id的值
接近 2 年之前 回复
半英里外的雨 具体如何转为json对象,您写的str应该是一个字符指针。因为初学,请多包涵。
接近 2 年之前 回复
oyljerry 回复qq_33672112: 转成json对象,然后_id是key
接近 2 年之前 回复
半英里外的雨 我写的代码和您给的差不多,我想要的是如何从str里提取_id信息,或者从doc提取_id信息,您说的用_id做key具体怎么做,请指教。
接近 2 年之前 回复
 bson_t query;
bson_t child;

BSON_APPEND_INT64(&query, "id", 0);

mongoc_cursor_t m_pCursor = mongoc_collection_find(m_pCollection,
    NULL,  /* Fields, NULL for all. */
    NULL); /* Read Prefs, NULL for default */

bson_error_t error;
if (mongoc_cursor_error(m_pCursor, &error)) {
    cout << "Query Failure: " << error.message;

const bson_t *doc;

while (!mongoc_cursor_error(m_pCursor, &error)
    && mongoc_cursor_more(m_pCursor))
    if (mongoc_cursor_next(m_pCursor, &doc))
if (mongoc_cursor_error(m_pCursor, &error)) {
    cout << "Query Failure: " << error.message;

半英里外的雨 回复dabocaiqq: GetRecord函数是要引用哪个头文件还是自己定义的,另外记录中包含的_id怎么提取。请指教
接近 2 年之前 回复
穷在人世中少你左右我想我连什么价值也没有 回复qq_33672112: 获取文档的记录
接近 2 年之前 回复
半英里外的雨 GetRecord(doc);起到什么作用
接近 2 年之前 回复
Csdn user default icon

<div class="post-text" itemprop="text"> <p>I'm using the mgo package for Mongo database interactions.</p> <p>I currently have a base struct that looks like:</p> <pre><code>type Document struct { ID bson.ObjectId `bson:"_id"` // Unique document _id. EntityId bson.ObjectId `bson:"entity_id"` // Used to create relationships between collections. EffectiveDate time.Time `bson:"effective_date"` // Date this document becomes effective. // Audit Fields. CreatedAt time.Time `bson:"created_at"` CreatedBy bson.ObjectId `bson:"created_by"` UpdatedAt time.Time `bson:"updated_at"` UpdatedBy bson.ObjectId `bson:"updated_by"` // Document state(stale, current, etc..) IsActive bool `bson:"is_active"` IsDeleted bool `bson:"is_deleted"` IsMaster bool `bson:"is_master"` ExternalID string `bson:"external_id"` CompanyID bson.ObjectId `bson:"company_id"` // The unique ObjectId for that company. } </code></pre> <p>I embedded this Document struct into more specific collection defined structs that look like:</p> <pre><code>// Represents a product-category document. type ProductCategory struct { Document // Embedded base document struct contains all base fields. Name string `bson:"name"` // Name of the category CategoryID string `bson:"category_id"` // Unique id of the category. } </code></pre> <p>I'm able to run queries like this one below and get all the fields I need besides the <code>bson.ObjectId</code> fields including ID(_id).</p> <pre><code> var pc collections.ProductCategory col := session.DB("some_db").C("product-category") col.Find(nil).One(&amp;pc) // All fields are here besides [Id, CompanyId, CreatedBy, UpdatedBy] etc.. </code></pre> <p>Is there any glaring issues on why the Fields I need aren't being added to the struct?</p> </div>

在Golang中的两个不同struct字段中映射Mongo _id

<div class="post-text" itemprop="text"> <p>I am working on a project that uses combination of Go and MongoDB. I am stuck at a place where I have a struct like:</p> <pre><code>type Booking struct { // booking fields Id int `json:"_id,omitempty" bson:"_id,omitempty"` Uid int `json:"uid,omitempty" bson:"uid,omitempty"` IndustryId int `json:"industry_id,omitempty" bson:"industry_id,omitempty"` LocationId int `json:"location_id,omitempty" bson:"location_id,omitempty"` BaseLocationId int `json:"base_location_id,omitempty" bson:"base_location_id,omitempty"` } </code></pre> <p>In this struct, the field <code>Id</code> is of <code>int</code> type. But as we know MongoDB's default id is of <code>bsonObject</code> type. Some times, the system generates the default MongoDB id in <code>Id</code> field.</p> <p>To overcome this I have modified the struct like this:</p> <pre><code>type Booking struct { // booking fields Id int `json:"_id,omitempty" bson:"_id,omitempty"` BsonId bson.ObjectId `json:"bson_id" bson:"_id,omitempty"` Uid int `json:"uid,omitempty" bson:"uid,omitempty"` IndustryId int `json:"industry_id,omitempty" bson:"industry_id,omitempty"` LocationId int `json:"location_id,omitempty" bson:"location_id,omitempty"` BaseLocationId int `json:"base_location_id,omitempty" bson:"base_location_id,omitempty"` } </code></pre> <p>In above struct, I have mapped the same <code>_id</code> field in two different struct fields Id (type int) and <code>BsonId</code> (type <code>bson.ObjectId</code>). I want if id of integer type comes, it maps under <code>Id</code> otherwise under <code>BsonId</code>.</p> <p>But this thing is giving following error:</p> <pre><code>Duplicated key '_id' in struct models.Booking </code></pre> <p>How can I implement this type of thing with Go Structs ??</p> <p><strong>Update:</strong></p> <p>Here is the code I have written for custom marshaling/unmarshaling:</p> <pre><code>func (booking *Booking) SetBSON(raw bson.Raw) (err error) { type bsonBooking Booking if err = raw.Unmarshal((*bsonBooking)(booking)); err != nil { return } booking.BsonId, err = booking.Id return } func (booking *Booking) GetBSON() (interface{}, error) { booking.Id = Booking.BsonId type bsonBooking *Booking return bsonBooking(booking), nil } </code></pre> <p>But this is giving type mismatch error of Id and BsonId fields. What should I do now ?</p> </div>


<div class="post-text" itemprop="text"> <p>In the mongodb there is a user data has been stored in collection <code>challange</code> the data seems like bellow:</p> <pre><code>{ "_id" : 1, "name" : "puneet", "last" : "jindal", "email" : "" } { "_id" : ObjectId("5b3af82cdb3aaa47792b5fd3"), "name" : "hardeep", "last" : "singh", "email" : "" } { "_id" : 3, "name" : "gaurav", "last" : "bansal", "email" : "" } { "_id" : ObjectId("5b3af87ddb3aaa47792b5fd4"), "name" : "manish", "last" : "jindal", "email" : "" } </code></pre> <p>In the above data there are four records and two of them having id in the integer form and other will having id in object form. I just want to retrieve the all the records which are having the <code>object id</code> in the id field. can anyone tell what query should I write in the code that will only retrieve that records which are having the object id.</p> <p>Updated:</p> <p>code I'm using :</p> <pre><code>type User struct { Id bson.ObjectId `json:"_id" bson:"_id,omitempty"` Name string `json:"name,omitempty" bson:"name,omitempty"` Last string `json:"last,omitempty" bson:"last,omitempty"` Email string `json:"email,omitempty" bson:"email,omitempty"` } type Users []User func GetAllUsers(listQuery interface{}) (result Users, err error) { mongoSession := config.ConnectDb() sessionCopy := mongoSession.Copy() defer sessionCopy.Close() getCollection := mongoSession.DB(config.Database).C(config.UsersCollection) err = getCollection.Find(listQuery).Select(bson.M{"password": 0}).All(&amp;result) if err != nil { return result, err } return result, nil } conditions := bson.M{'_id': bson.M{'$type': "objectId" } } data, err := models.GetAllUsers(conditions) </code></pre> <p>The error I'm facing by using this :-</p> <blockquote> <p>controllers/UserController.go:18:23: invalid character literal (more than one character) controllers/UserController.go:18:28: cannot use '\u0000' (type rune) as type string in map key</p> </blockquote> </div>

mongoDB Golang Bson界面有问题吗?

<div class="post-text" itemprop="text"> <p>I uesd MongoDB v3.6.4 with mgo( package</p> <p>Bson </p> <pre><code>var id interface{} id = 249678041972736 bson.M{"_id": id} var id int64 id = 249678041972736 bson.M{"_id": id} </code></pre> <p>Tow bsons are not same?<br> eg: </p> <pre><code>func GetUser(id interface{}) (*User, error) { session := MongoDB() defer session.Close() var m *User err := session.DB.C("user").Find(&amp;bson.M{"_id": id}).One(&amp;m) // !!!err: not found if err != nil { return nil, err } else { return m, nil } } </code></pre> <p>but: </p> <pre><code>func GetUser(id int64) (*User, error) { session := MongoDB() defer session.Close() var m *User err := session.DB.C("user").Find(&amp;bson.M{"_id": id}).One(&amp;m) // !!! err == nil if err != nil { return nil, err } else { return m, nil } } GetUser(id interface{}) can get err (not found) GetUser(id int64) can get nil err </code></pre> <p>Pay attention to error </p> <p>I used function GetUser and import same value 249678041972736 but different parameter type get differents result</p> <p>why???</p> </div>

MongoDB bson.M查询

<div class="post-text" itemprop="text"> <p>I am trying to query using bison all JSON data in MongoDB with two fields but am getting null as result.</p> <pre><code>{ "allowedList": [ { "List": [ { "allow": { "ss": 1, }, "Information": [ { "Id": "Id1" } ] } ] } ] } </code></pre> <p>I was able to filter all using the MongoDB at command line using</p> <pre><code> db.slicedb.find({"":1,"allowedList.List.Information.nsiId":"Id-Id21"}) but using query := bson.M{"allowedList.List.allow": bson.M{"ss": sst}, "allowedList.List.Information": bson.M{"Id": Id}} </code></pre> <p>sst and Id are integer and string input to the query function</p> <pre><code>err := db.C(COLLECTION).Find(query).All(&amp;specificSlices) </code></pre> <p>but is not working, am getting null even though there are json data that match the two field. Can someone help point out what was wrong with my query? </p> <p>Server and database config</p> <pre><code>type SliceDataAccess struct { Server string Database string } var db *mgo.Database const ( COLLECTION = "slicedb" ) </code></pre> <p>Establish a connection to database</p> <pre><code>func (m *SliceDataAccess) Connect() { session, err := mgo.DialWithTimeout(m.Server, 20*time.Second) if err != nil { log.Fatal(err) } db = session.DB(m.Database) } </code></pre> <p>Structs fields </p> <pre><code>type InstanceInfo struct { ID string `json:"nfId" bson:"_id"` AllowedList []AllowedNssai `json:"allowedList" bson:"allowedList"` } type AllowedNssai struct { List []AllowedSnssai `json:"List,omitempty" bson:"List"` ... } type AllowedSnssai struct { Allow *Snssai `json:"allow,omitempty" bson:"allow"` Information []NsiInformation `json:"Information,omitempty" bson:"Information"` } type NsiInformation struct { Id string `json:"Id" bson:"Id"` } type Snssai struct { Ss int32 `json:"sst" bson:"ss"` } </code></pre> <p>Query function defined</p> <pre><code>func (m *SliceDataAccess) FindAll(sst int32, nsiId string ([]InstanceInfo, error) { var specificSlices []InstanceInfo query := bson.M{"allowedList.List.allow": bson.M{"ss": sst}, "allowedList.List.Information": bson.M{"Id": nsiId}} err := db.C(COLLECTION).Find(query).All(&amp;specificSlices) if err != nil { return specificSlices, err } return specificSlices, nil } </code></pre> <p>HTTP handler function for request and response</p> <pre><code>func AvailabilityGet(w http.ResponseWriter, r *http.Request) var slice InstanceInfo err := json.NewDecoder(r.Body).Decode(&amp;slice) if err != nil { respondWithError(w, http.StatusBadRequest, "Object body not well decoded") return } sst := slice.AllowedList[0].List[0].Allow.Sst nsiId := slice.AllowedList[0].List[0].Information[0].Id specificSlices, err := da.FindAll(sst, nsiId) json.NewEncoder(w).Encode(specificSlices) } </code></pre> <p>Attached is my the full go code i have done. </p> </div>


<div class="post-text" itemprop="text"> <p>This is golang. My problem is in the collection search by IDs</p> <p>I want to find several collections with an array of IDs</p> <p>This is the document</p> <pre><code>/*document with name brands*/ { first_id : "100" second_id : "200" name : "adidas", description: "clothing" } { first_id : "101" second_id : "202" name : "ferrari", description: "auto" } </code></pre> <p>This is the collection model</p> <pre><code>type Brand struct { FirstID string `bson:"first_id" json:"first_id"` SecondID string `bson:"second_id" json:"second_id"` Name *string `bson:"name" json:"name"` Description *string `bson:"description" json:"description"` } </code></pre> <p>This function performs the search by IDs, here is the problem</p> <pre><code>func searchByID(collection *mongo.Collection) { ids := [][]string{{"100", "200"}, {"101", "202"}} filter2 := bson.M{"first_id,second_id": ids} // This is the problem cursor, err := collection.Find(context.Background(), filter2) brands := []Brand{} if err == nil { for cursor.Next(context.Background()) { brand := Brand{} cursor.Decode(&amp;brand) brands = append(brands, brand) } } else { print(err.Error()) } print("print the brands") print(brands) //Result [] } </code></pre> </div>


<div class="post-text" itemprop="text"> <p>I'm trying to code a simple web app in Go using Mongodb. I've created a minimalistic simple Model / Controller setup. I can create new user using POST with url "/user" with data such as '{"pseudo": "bobby1"}'. The user is created. However, when looking inside Mongodb shell, I get:</p> <pre><code>{ "_id" : ObjectId("5616d1ea56ca4dbc03bb83bc"), "id" : ObjectId("5616d1ea5213c64824000001"), "pseudo" : "bobby2"} </code></pre> <p>The "id" field is the one coming from my struct and the "_id" field is the one from Mongodb. From looking at different sample code, it looked like I could use myself the one from Mongodb but I can't find how to do it.. &gt;&lt; Since the "id" is only used by me, I can't find user by their ID since I do not have that one... More over, when I do a GET /user, it returns the full list of user, and I only get:</p> <pre><code>{"id":"5616d1ea5213c64824000001","pseudo":"bobby2" </code></pre> <p>Not the "real" Mongodb Id...</p> <p>Thanks,</p> <p>Here's the code:</p> <p><strong>model/user.go</strong></p> <pre><code>const userCollection = "user" // Get our collection var C *mgo.Collection = database.GetCollection(userCollection) // User represents the fields of a user in db type User struct { Id bson.ObjectId `json:"id"i bson:"_id,omitempty"` Pseudo string `json:"pseudo" bson:"pseudo"` } // it will return every users in the db func UserFindAll() []User { var users []User err := C.Find(bson.M{}).All(&amp;users) if err != nil { panic(err) } return users } // UserFIndId return the user in the db with // corresponding ID func UserFindId(id string) User { if !bson.IsObjectIdHex(id) { s := fmt.Sprintf("Id given %s is not valid.", id) panic(errors.New(s)) } oid := bson.ObjectIdHex(id) u := User{} if err := C.FindId(oid).One(&amp;u); err != nil { panic(err) } return u } // UserCreate create a new user on the db func UserCreate(u *User) { u.Id = bson.NewObjectId() err := C.Insert(u) if err != nil { panic(err) } } </code></pre> <p><strong>controller/user.go</strong></p> <pre><code>/ GetAll returns all users func (us *UserController) GetAll(w http.ResponseWriter, request *http.Request) { // u := model.User{ // ID: "987654321", // Pseudo: "nikko", // } users := model.UserFindAll() bu, err := json.Marshal(users) if err != nil { fmt.Printf("[-] Error while marshaling user struct : %v ", err) w.Write([]byte("Error Marshaling")) w.WriteHeader(404) return } w.Header().Set("Content-type", "application/json") w.WriteHeader(200) fmt.Fprintf(w, "%s ", bu) } // Get return a specific user according to Id func (us *UserController) Get(w http.ResponseWriter, request *http.Request) { vars := mux.Vars(request) ps := vars["id"] u := model.UserFindId(ps) bu, err := json.Marshal(u) if err != nil { fmt.Printf("[-] Error while marshaling user struct : %v ", err) w.Write([]byte("Error Marshaling")) w.WriteHeader(404) return } w.Header().Set("Content-type", "application/json") w.WriteHeader(200) fmt.Fprintf(w, "%s ", bu) } func (us *UserController) Post(w http.ResponseWriter, r *http.Request) { u := model.User{} json.NewDecoder(r.Body).Decode(&amp;u) model.UserCreate(&amp;u) bu, err := json.Marshal(u) if err != nil { fmt.Printf("[-] Error PUT user struct : %v ", err) w.WriteHeader(404) return } w.Header().Set("Content-type", "application/json") w.WriteHeader(201) fmt.Fprintf(w, "%s ", bu) } </code></pre> </div>

Golang Mgo通过ID(Mongodb)填充嵌套结构

<div class="post-text" itemprop="text"> <p>Using mongoose with NodeJs for document population to simulate joins is very common. I'm trying to understand how to achieve something similar with go and mgo.</p> <pre><code>type User struct { Id bson.ObjectId `json:"_id" bson:"_id"` UserName string } type MessageBoard { Id bson.ObjectId `json:"_id" bson:"_id"` } type Tag struct { Id bson.ObjectId `json:"_id" bson:"_id"` text string } type Post struct { Id bson.ObjectId `json:"_id" bson:"_id"` Text string MessageBoard bson.ObjectId User bson.ObjectId Tags []bson.ObjectId } </code></pre> <p>I would like to store only User and Tag ids in Post. A user can have many posts and if the user edits UserName all posts should reflect this.</p> <pre><code>var posts []Post err := PostCollection.Find(bson.M{"MessageBoard":mBoardId}).All(&amp;posts) if err != nil { return nil, err } </code></pre> <p>This is a simple query to get posts, but how do I efficiently get posts with User and Tags models populated?</p> <p>There is Sleep (an Mgo extension) which appears to do what I am looking for, but I am interested in understanding the performance implications and design options better and if there is a solution using Mgo alone. <a href="" rel="nofollow"></a></p> </div>


<div class="post-text" itemprop="text"> <p>So here is my question. I have an array which are stored the <code>_ids</code> of mongodbs objects. Whats the right way to retrieve them all in one query using the mgo and bson package?</p> <p>So if the array is like that: <code>ids:=["543d171c5b2c12420dd016","543d171c5b2dd016"]</code></p> <p>How we make the query ? I tried that but I know its wrong.</p> <pre><code>query := bson.M{"_id": bson.M{"$in": ids}} c.Find(query).All() </code></pre> <p>Thanks in advance</p> </div>

如何编写Golang bson-MongoDB

<div class="post-text" itemprop="text"> <p>Am trying to write the golang bson query for this mongodb query but cannot. Can anyone help? I can query mongo shell with the command</p> <pre><code>db.collection.find({"nfType": "SMF"},{"_id": 0,"ipv4Addresses": 1}) </code></pre> <p>which gives the output that i want as</p> <pre><code>[{ "ipv4Addresses": [""]}] </code></pre> <p>Now am trying to write a golang bson for this query to get only the ipv4Addresses field as shown above but cannot. The document in the collection is of the form</p> <pre><code>{ "nfType": [ "SMF" ], "nfStatus": [ "REG" ], "sNssais": [ { "sst": 1, "sd": "sd1" } ], "nsiList": [ "NSI-ID1" ], "ipv4Addresses": [ "" ] } </code></pre> </div>

golang mongodb(mgo)未插入文档

<div class="post-text" itemprop="text"> <p>Im having issues with persisting a golang struct in mongodb using mgo. </p> <pre><code>type AN_Track_Log struct { Id bson.ObjectId `bson:"_id,omitempty"` user_session_id_str string `bson:"user_session_id_str"` googleanaly_pixel_id_str string `bson:"googleanaly_pixel_id_str"` perfaud_pixel_id_str string `bson:"perfaud_pixel_id_str"` site_id_str string `bson:"site_id_str"` metric_str string `bson:"metric_str"` value_str string `bson:"value_str"` event_str string `bson:"event_str"` location_id_str string `bson:"location_id_str"` referer_str string `bson:"referer_str"` track_origin_str string `bson:"track_origin_str"` fingerprint_str string `bson:"fingerprint_str"` ... } p_track_log.Id = bson.NewObjectId() err := p_mongodb_coll.Insert(&amp;p_track_log) </code></pre> <p>the problem is that when the Insert() call completes, the only thing thats persisted in the DB is an empty doc</p> <pre><code>{u'_id': ObjectId('561809d20037873154000003')} </code></pre> <p>I check that the struct fields are indeed set, and not empty. Any ideas as to why this is happening. Hints are appreciated :) thank you</p> </div>


<div class="post-text" itemprop="text"> <p>I want to fetch mongodb collection with multiple conditions but I am getting the error:</p> <pre><code>panic: Failed to parse: filter: [ { visibility: { $eq: "4" } }, { discontinued: { $ne: "1" } }, { status: { $eq: "1" } } ]. 'filter' field must be of BSON type Object. </code></pre> <p>The code is as follow:</p> <pre><code>package main import ( "fmt" "" ) func GenerateFeed(headers, attributes interface{}, conditions []interface{}) { var operations = []bson.M{} for _, val := range conditions { var attr, operator, value interface{} cons := val.(map[interface{}]interface{}) for range cons { attr = cons["attribute"] operator = cons["operator"] value = cons["value"] switch operator { case "==": operator = "$eq" case "!=": operator = "$ne" case "()": operator = "$in" } } operations = append(operations, bson.M{attr.(string): bson.M{operator.(string): value}}) } var products []Prod session := Connect() collection := session.DB("rfgv2").C("catalog_product_entity_1") err := collection.Find(operations).All(&amp;products) CheckError(err) fmt.Println(products) } type Prod struct { EntityId string `bson:"entity_id"` Name string `bson:"name"` TypeId string `bson:"type_id"` Sku string `bson:"sku"` Manufacturer int32 `bson:"manufacturer"` Status int32 `bson:"status"` Visibility int32 `bson:"visibility"` EnableGoogleCheckout int32 `bson:"enable_google_checkout"` Delivery string `bson:"delivery"` MetaTitle string `bson:"meta_title"` MetaDescription string `bson:"meta_description"` Image string `bson:"image"` SmallImage string `bson:"small_image"` Thumbnail string `bson:"thumbnail"` Gallery string `bson:"gallery"` UrlKey string `bson:"url_key"` UrlPath string `bson:"url_path"` Mpn string `bson:"mpn"` ProductListingAds string `bson:"product_listing_ads"` Color string `bson:"color"` Price float32 `bson:"price"` Cost float32 `bson:"cost"` TierPriceForBundle float32 `bson:"tier_price_for_bundle"` RegularPrice float32 `bson:"regular_price"` SpecialFromDate string `bson:"special_from_date"` Description string `bson:"description"` MetaKeyword string `bson:"meta_keyword"` Dimensions string `bson:"dimensions"` Features string `bson:"features"` DeliveryPopupMessage string `bson:"delivery_popup_message"` CreatedAt string `bson:"created_at"` UpdatedAt string `bson:"updated_at"` } </code></pre> <p>I am trying to fetch records based on multiple aggregate functions from mongodb with go. Basically if we remove the square brackets and try with mongo command it works, but how to fix this in go?</p> <p>Thank You. </p> </div>


<div class="post-text" itemprop="text"> <p>I'm trying to find a document by its auto generated _id field. Code below returns nothing:</p> <pre><code>var documentID bson.RawValue documentID.Type = 7 documentID.Value = []byte("5c7452c7aeb4c97e0cdb75bf") objID := documentID.ObjectID() value := collection.FindOne(ctx, bson.M{"_id": objID}) </code></pre> <p>The value I provided is a real document id I got from Mongo Express </p> <pre><code>"_id": ObjectID("5c7452c7aeb4c97e0cdb75bf") </code></pre> <p>In case you're wondering why I bother with RawValue, I found examples using bson.EC.ObjectID but bson package doesn't seem to have EC type, also I found some examples mentioning package, but I could not find that package either. I previously developed with mgo but I'm new to mongo-go-driver, so if you can point an easy way to declare an ObjectID. </p> </div>

最近在看MongoDB的一些内容,关于BSON这种格式存储格式,看到一些文章说它是"schemaless" 的。 schemaless 到底是什么意思

最近在看MongoDB的一些内容,关于BSON这种格式存储格式,看到一些文章说它是"schemaless" 的。 我在网上查找资料,没有找到很好的介绍资料。各位大佬能否帮忙指点一二

如何使用golang在mongodb中对具有相同user_id的收集数据进行$ group?

<div class="post-text" itemprop="text"> <p>I'm trying to make the sum of the price of the product which having same <code>user_id</code> using golang. But I don't know how I will get this. I tried <code>$group</code> in the following code</p> <p>Struct for product</p> <pre><code>type Product struct { Id int `json:"id" bson:"_id"` Name string `json:"name" bson:"name"` Sku string `json:"sku" bson:"sku"` Category string `json:"category" bson:"category"` Stock int `json:"stock" bson:"stock"` Price float64 `json:"price" bson:"price"` Sale_price float64 `json:"sale_price" bson:"sale_price"` UpdatedOn int64 `json:"updated_on" bson:"updated_on"` UserId int `json:"user_id" bson:"user_id"` } </code></pre> <p>Struct for the customer</p> <pre><code>type Customer struct { Id int `json:"id" bson:"_id"` FirstName string `json:"first_name" bson:"first_name"` LastName string `json:"last_name" bson:"last_name"` Email string `json:"email" bson:"email"` PhoneNumber string `json:"phone_number" bson:"phone_number"` } </code></pre> <p>function from where the data will retrieve </p> <pre><code>func GetProducts(c *gin.Context) { mongoSession := config.ConnectDb() //connection to database collection := mongoSession.DB(config.Database).C(config.ProductCollection) //session pipeline := []bson.M{ bson.M{"$group": bson.M{"user_id": 1}}, bson.M{"$sum": bson.M{"price": "price"}}, } //query i tried fmt.Println(pipeline) pipe := collection.Pipe(pipeline) resp := []bson.M{} err = pipe.All(&amp;resp) if err != nil { fmt.Println("Errored: %#v ", err) } fmt.Println(resp) GetResponseList(c, response) } </code></pre> <p>The data viewed in the image-</p> <p><a href="" rel="nofollow noreferrer"><img src="" alt=""></a></p> <p>In the above image the <code>user_id</code> of the product is same. I want to group this data and calculate the <code>price</code>.</p> <p>I also read the documentation of the Mongodb <a href="" rel="nofollow noreferrer">this one</a> but don't understand how to do in golang can anyone explain it in simple way how to make the query for this. Thanks</p> </div>

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>

将MongoDB查询发送到其他系统:转换为JSON,然后解码为BSON? 用Go语言怎么做?

<div class="post-text" itemprop="text"> <p>I need to transfer a MongoDB query to a different system. For this reason I would like to use the <a href="" rel="nofollow">MongoDB Extended JSON</a>. I need this to be done mostly because I use date comparisons in my queries.</p> <p>So, the kernel of the problem is that I need to transfer a MongoDB query that has been generated in a <em>node.js</em> back-end to another back-end written in <em>Go</em> language.</p> <p>Intuitively, the most obvious format for sending this query via <em>REST</em>, is JSON. But, MongoDB queries are not exactly JSON, but BSON, which contains special constructs for dates.</p> <p>So, the idea is to convert the queries into JSON using <a href="" rel="nofollow">MongoDB Extended JSON</a> as form of representation of the special constructs. After some tests it's clear that these queries do not work. Both the MongoDB shell and queries sent via <em>node.js</em>'s need the special <code>ISODate</code> or <code>new Date</code> constructs.</p> <p>Finally, the actual question: are there functions to encode/decode from JSON to BSON, taking into account <a href="" rel="nofollow">MongoDB Extended JSON</a>, both in JavaScript (node.js) and <em>Go</em> language?</p> <h1>Updates</h1> <h2>Node.js encoding package</h2> <p>Apparently <a href="" rel="nofollow">there is a <em>node.js</em> package</a> that parses and stringifies BSON/JSON. So, half of my problem is resolved. I wonder if there is something like this in <em>Go</em> language. </p> <h2>Sample query</h2> <p>For example, the following query is in normal BSON:</p> <pre><code>{ Tmin: { $gt: ISODate("2006-01-01T23:00:00.000Z") } } </code></pre> <p>Translated into <em>MongoDB Extended JSON</em>, it becomes:</p> <pre><code>{ "Tmin": { "$gt" : { "$date" : 1136156400000 }}} </code></pre> </div>

问题是使用golang bson从mongo获取整个元素,而仅返回了子元素

<div class="post-text" itemprop="text"> <p>I am working on a mongo query in golang using mgo to query a child element to return the entire element </p> <pre><code>{ "_id" : ObjectId("5b64a0d3931653c36bcaf0b5"), "quantity" : 2, "product" : "ABC", "children" : [ { "isBlocked" : true, "blockedMessage" : "Error occurred: TRACEID", "serialNo" : "abc123", "token" : "foo456", } ] } </code></pre> <p>The query I am using in below bson.M{"_id": 0, "children": bson.M{"$elemMatch": {serialNo: 'abc123'}}}</p> <pre><code>Find(MongoSpec{Selector: bson.M{}, Query: bson.M{"_id": 0, "children": bson.M{"$elemMatch": fields}}}) </code></pre> <p>Below is the find function</p> <pre><code> documents := []interface{}{} s := spec.(MongoSpec).Selector q := spec.(MongoSpec).Query query := session. DB(repo.Config.DatabaseName). C(repo.CollectionName). Find(s) if q != nil { query = query.Select(q) } err := query.All(&amp;documents) </code></pre> <p>MongoSpec struct </p> <pre><code> type MongoSpec struct { Selector interface{} Query interface{} } </code></pre> <p>The above query works fine but returns only children element as below</p> <pre><code>"children" : [ { "isBlocked" : true, "blockedMessage" : "Error occurred: TRACEID", "serialNo" : "abc123", "token" : "foo456", } ] </code></pre> <p>I am not getting what is wrong with the query.</p> </div>


<div class="post-text" itemprop="text"> <p>I am trying to combine some filters with no success. I am using the mongodb driver for go</p> <pre><code>// FindOneByID returns an error on fail, otherwise, it sets the {out} by the result. func FindOneByID(collectionName string, id *primitive.ObjectID, out interface{}, considerArchivedItems bool) error { ctx, _ := context.WithTimeout(context.Background(), 2*time.Second) var filter bson.M if considerArchivedItems { filter = bson.M{"_id": id} } else { filter = bson.M{"$and": bson.A{ bson.M{"_id": id}, bson.M{isArchived: bson.M{"$ne": false}}}} } return database.Collection(collectionName).FindOne(ctx, filter).Decode(out) } </code></pre> <p>Now, I insert an object as archived and trying to get the document. The document is inserted as archived, so I want to consider archived items.</p> <p>However, when I pass in the <code>else</code>, document can be either archived or not (<code>false</code> or <code>true</code>), I still get it anyway. So it means that my $and doesn’t work..</p> <pre><code>const ( databaseNameUnitTests = "database_name_unit_tests" databaseCollectionNameUnitTests = "database_name_unit_tests" ) type Test struct { ID *primitive.ObjectID `protobuf:"bytes,1,opt,name=id,proto3" json:"_id,omitempty" bson:"_id,omitempty"` IsArchived bool `protobuf:"varint,2,opt,name=IsArchived,proto3" json:"is_archived,omitempty" bson:"is_archived,omitempty"` Description string `protobuf:"varint,3,opt,name=Description,proto3" json:"description,omitempty" bson:"description,omitempty"` } // func var item Test err := mongodb.FindOneByID(databaseCollectionNameUnitTests, insertedID, &amp;item, false) </code></pre> <p>The following query from Robo 3T : <code>db.getCollection('database_name_unit_tests').find({$and:[{"_id":ObjectId("5d2e8afeb0e106fbe0d5af21")},{"is_archived": {$ne:false}}]})</code> this works tho, where am I wrong?</p> </div>

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

Vue + Spring Boot 项目实战(十九):Web 项目优化解决方案



CopyOnWriteArrayList.java和,这2个类的构造函数,注释中有一句话 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 public ArrayList(Collection&lt;? ...


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


CSDN:因博主近期注重写专栏文章(已超过150篇),订阅博主专栏人数在突增,近期很有可能提高专栏价格(已订阅的不受影响),提前声明,敬请理解! 目录 博客声明 大数据了解博主粉丝 博主的粉丝群体画像 粉丝群体性别比例、年龄分布 粉丝群体学历分布、职业分布、行业分布 国内、国外粉丝群体地域分布 博主的近期访问每日增量、粉丝每日增量 博客声明 因近期博主写专栏的文章越来越多,也越来越精细,逐步优化文章。因此,最近一段时间,订阅博主专栏的人数增长也非常快,并且专栏价


一个HashMap能跟面试官扯上半个小时 关注 安琪拉的博客 1.回复面试领取面试资料 2.回复书籍领取技术电子书 3.回复交流领取技术电子书 前言 HashMap应该算是Java后端工程师面试的必问题,因为其中的知识点太多,很适合用来考察面试者的Java基础。 开场 面试官: 你先自我介绍一下吧! 安琪拉: 我是安琪拉,草丛三婊之一,最强中单(钟馗不服)!哦,不对,串场了,我是**,目...




我在年前从上一家公司离职,没想到过年期间疫情爆发,我也被困在家里,在家呆着的日子让人很焦躁,于是我疯狂的投简历,看面试题,希望可以进大公司去看看。 我也有幸面试了我觉得还挺大的公司的(虽然不是bat之类的大厂,但是作为一名二本计算机专业刚毕业的大学生bat那些大厂我连投简历的勇气都没有),最后选择了中软,我知道这是一家外包公司,待遇各方面甚至不如我的上一家公司,但是对我而言这可是外包华为,能...


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


接着上回说,培训班学习生涯结束了。后面每天就是无休止的背面试题,不是没有头脑的背,培训公司还是有方法的,现在回想当时背的面试题好像都用上了,也被问到了。回头找找面试题,当时都是打印下来天天看,天天背。 不理解呢也要背,面试造飞机,上班拧螺丝。班里的同学开始四处投简历面试了,很快就有面试成功的,刚开始一个,然后越来越多。不知道是什么原因,尝到胜利果实的童鞋,不满足于自己通过的公司,嫌薪水要少了,选择...

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





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


近日,有网友在某职场社交平台吐槽,自己裸辞两个月了,但是找工作却让自己的心态都要崩溃了,全部无果,不是已查看无回音,就是已查看不符合。 “工作八年,两年一跳,裸辞两个月了,之前月薪60K,最近找工作找的心态崩了!所有招聘工具都用了,全部无果,不是已查看无回音,就是已查看不符合。进头条,滴滴之类的大厂很难吗???!!!投简历投的开始怀疑人生了!希望 可以收到大厂offer” 先来看看网...


导读 前天面试了一个985高校的实习生,问了他平时用什么开发工具,他想也没想的说IDEA,于是我抛砖引玉的问了一下IDEA的调试用过吧,你说说怎么设置断点...

都前后端分离了,咱就别做页面跳转了!统统 JSON 交互

文章目录1. 无状态登录1.1 什么是有状态1.2 什么是无状态1.3 如何实现无状态1.4 各自优缺点2. 登录交互2.1 前后端分离的数据交互2.2 登录成功2.3 登录失败3. 未认证处理方案4. 注销登录 这是本系列的第四篇,有小伙伴找不到之前文章,松哥给大家列一个索引出来: 挖一个大坑,Spring Security 开搞! 松哥手把手带你入门 Spring Security,别再问密...


这是世界编程大赛第一名作品(97年Mekka ’97 4K Intro比赛)汇编语言所写。 整个文件只有4095个字节, 大小仅仅为16KB! 不仅实现了3D动画的效果!还有一段震撼人心的背景音乐!!! 内容无法以言语形容,实在太强大! 下面是代码,具体操作看最后! @echo off more +1 %~s0|debug e100 33 f6 bf 0 20 b5 10 f3 a5...


昨天,有位大一的同学私信我,说他要做全栈工程师。 我一听,这不害了孩子么,必须制止啊。 谁知,讲到最后,更确定了他做全栈程序员的梦想。 但凡做全栈工程师的,要么很惨,要么很牛! 但凡很牛的,绝不是一开始就是做全栈的! 全栈工程师听起来好听,但绝没有你想象的那么简单。 今天听我来给你唠,记得帮我点赞哦。 一、全栈工程师的职责 如果你学习编程的目的只是玩玩,那随意,想怎么学怎么学。...

不要再到处使用 === 了

我们知道现在的开发人员都使用 === 来代替 ==,为什么呢?我在网上看到的大多数教程都认为,要预测 JavaScript 强制转换是如何工作这太复杂了,因此建议总是使用===。这些都...


A站 AcFun弹幕视频网,简称“A站”,成立于2007年6月,取意于Anime Comic Fun,是中国大陆第一家弹幕视频网站。A站以视频为载体,逐步发展出基于原生内容二次创作的完整生态,拥有高质量互动弹幕,是中国弹幕文化的发源地;拥有大量超粘性的用户群体,产生输出了金坷垃、鬼畜全明星、我的滑板鞋、小苹果等大量网络流行文化,也是中国二次元文化的发源地。 B站 全称“哔哩哔哩(bilibili...


文章目录前言正文**1、Kaspersky Cyberthreat real-time map****2、Finding Home****3、Silk – Interactive Generative Art****4、Liquid Particles 3D****5、WINDOWS93****6、Staggering Beauty****7、Ostagram图片生成器网址****8、全历史网址*...



用了这个 IDE 插件,5分钟解决前后端联调!

点击上方蓝色“程序猿DD”,选择“设为星标”回复“资源”获取独家整理的学习资料!作者 |李海庆我是一个 Web 开发前端工程师,受到疫情影响,今天是我在家办公的第78天。开发了两周,...

大厂的 404 页面都长啥样?最后一个笑了...

每天浏览各大网站,难免会碰到404页面啊。你注意过404页面么?猿妹搜罗来了下面这些知名网站的404页面,以供大家欣赏,看看哪个网站更有创意: 正在上传…重新上传取消 腾讯 正在上传…重新上传取消 网易 淘宝 百度 新浪微博 正在上传…重新上传取消 新浪 京东 优酷 腾讯视频 搜...


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


某站后端代码被“开源”,同时刷遍全网的,还有代码里的那些神注释。 我们这才知道,原来程序员个个都是段子手;这么多年来,我们也走过了他们的无数套路… 首先,产品经理,是永远永远吐槽不完的!网友的评论也非常扎心,说看这些代码就像在阅读程序员的日记,每一页都写满了对产品经理的恨。 然后,也要发出直击灵魂的质问:你是尊贵的付费大会员吗? 这不禁让人想起之前某音乐app的穷逼Vip,果然,穷逼在哪里都是...

Java14 新特性解读

Java14 已于 2020 年 3 月 17 号发布,官方特性解读在这里:以下是个人对于特性的中文式...




小弟最近在学校无聊的很哪,浏览网页突然看到一张图片,都快流鼻血。。。然后小弟冥思苦想,得干一点有趣的事情python 爬虫库安装


作者:小傅哥 博客: 沉淀、分享、成长,让自己和他人都能有所收获! 一、前言 最近有伙伴问小傅哥,我的简历怎么投递了都没有反应,心里慌的很呀。 工作两年了目前的公司没有什么大项目,整天的维护别人的代码,有坑也不让重构,都烦死了。荒废我一身技能无处施展,投递的简历也没人看。我是不动物园里的猩猩,狒狒了! 我要加班,我要996,我要疯狂编码,求给我个机会… ...

相关热词 c# 局部 截图 页面 c#实现简单的文件管理器 c# where c# 取文件夹路径 c# 对比 当天 c# fir 滤波器 c# 和站 队列 c# txt 去空格 c#移除其他类事件 c# 自动截屏