已经通过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>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>


<div class="post-text" itemprop="text"> <p>I'm learning how to use the community maintained <code>mgo</code> repo linked <a href="" rel="nofollow noreferrer">here</a>.</p> <p>I've discovered through this <a href="" rel="nofollow noreferrer">example</a> that the way to query for some pieces of data seems to be done through BSON (The community maintained version of the BSON library is linked <a href="" rel="nofollow noreferrer">here</a>):</p> <pre><code>type Person struct { Name string Phone string } c.Find(bson.M{"name": "Alice"}).All(&amp;result) </code></pre> <p>Which will give me all <code>Person</code> with name <code>Alice</code>.</p> <p>I have also discovered that I don't need BSON to do this query. <code>Find()</code> takes any interface:</p> <pre><code>c.Find(Person{ Name: "Alice", Phone: "1234", }).All(&amp;result) </code></pre> <p>Will also work, but only returning the specified exact query. If I leave out piece of the struct like this:</p> <pre><code>c.Find(Person{ Name: "Alice", }).All(&amp;result) </code></pre> <p><code>result</code> will be empty.</p> <hr> <p>It seems to me that avoiding BSON is more intuitive and simpler. So my questions are:</p> <ol> <li>Should I avoid the BSON import?</li> <li>Can I query for all matching patterns without using BSON or specifying the entire interface?</li> <li>Should I specify BOTH JSON and BSON keys like in <code>json:"name"</code> or are they interchangeable?</li> </ol> </div>


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

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>

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>


<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>What I am looking is equivalent of <a href="" rel="noreferrer">Document.parse()</a></p> <p>in golang, that allows me create bson from json directly? I do not want to create intermediate golang structs for marshaling</p> </div>

如何使用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>


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


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

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>


<div class="post-text" itemprop="text"> <p>I have the structures below. I use <strong>Golang 1.9.2</strong>.</p> <pre><code>// EventBoost describes the model of a EventBoost type EventBoost struct { ID string `bson:"_id" json:"_id" valid:"alphanum,printableascii"` CampaignID string `bson:"_campaign_id" json:"_campaign_id" valid:"alphanum,printableascii"` Name string `bson:"name" json:"name"` Description string `bson:"description" json:"description"` Level string `bson:"level" json:"level"` EventID string `bson:"_event_id" json:"_event_id" valid:"alphanum,printableascii"` StartDate time.Time `bson:"start_date" json:"start_date"` EndDate time.Time `bson:"end_date" json:"end_date"` IsPublished bool `bson:"is_published" json:"is_published"` CreatedBy string `bson:"created_by" json:"created_by"` CreatedAt time.Time `bson:"created_at" json:"created_at"` ModifiedAt time.Time `bson:"modified_at" json:"modified_at"` } // LocationBoost describes the model of a LocationBoost type LocationBoost struct { ID string `bson:"_id" json:"_id" valid:"alphanum,printableascii"` CampaignID string `bson:"_campaign_id" json:"_campaign_id" valid:"alphanum,printableascii"` Name string `bson:"name" json:"name"` Description string `bson:"description" json:"description"` Level string `bson:"level" json:"level"` LocationID string `bson:"_location_id" json:"_location_id" valid:"alphanum,printableascii"` StartDate time.Time `bson:"start_date" json:"start_date"` EndDate time.Time `bson:"end_date" json:"end_date"` IsPublished bool `bson:"is_published" json:"is_published"` CreatedBy string `bson:"created_by" json:"created_by"` CreatedAt time.Time `bson:"created_at" json:"created_at"` ModifiedAt time.Time `bson:"modified_at" json:"modified_at"` } // Campaign describes the model of a Campaign type Campaign struct { ID string `bson:"_id" json:"_id" valid:"alphanum,printableascii"` Name string `bson:"name" json:"name"` Description string `bson:"description" json:"description"` EventBoostIDs []string `bson:"event_boost_ids" json:"event_boost_ids"` LocationBoostIDs []string `bson:"location_boost_ids" json:"location_boost_ids"` StartDate time.Time `bson:"start_date" json:"start_date"` EndDate time.Time `bson:"end_date" json:"end_date"` IsPublished bool `bson:"is_published" json:"is_published"` CreatedBy string `bson:"created_by" json:"created_by"` CreatedAt time.Time `bson:"created_at" json:"created_at"` ModifiedAt time.Time `bson:"modified_at" json:"modified_at"` } </code></pre> <p>A <strong>Campaign</strong> (understand a marketing campaign) is made of <strong>Events</strong> or <strong>Locations</strong> that can be boosted with a level (basic or premium). A campaign has a start and a end date, so do have the boosts.</p> <p>The function <code>GetEventLevel</code> has to return me the level of a given event.</p> <pre><code>// GetEventLevel of an event func (dao *campaignDAO) GetEventLevel(eventID string) (string, error) { } </code></pre> <p>If the event is boosted in <em>an active campaign</em> (<code>isPublished</code> is <code>true</code>), and <em>the boost is active</em> (<code>isPublished</code> is <code>true</code>) and <em>the now date is between the start and end date of the boost</em>, then my Event is <strong>boosted</strong>, so the function returns the level (basic or premium). Else, it returns <code>"standard"</code>.</p> <p>My question is : <strong>can I do this fully with Mongo ? Or do I need to perform some logic in the DAO with Golang ?</strong></p> <p>If I can do this with Mongo, what I hope, I have no idea how to do this. From what I understand, I would first need to lookup the events and the locations of the campaign, and then search in it with dates, but..</p> </div>


<div class="post-text" itemprop="text"> <p>I looking return default value for new struct, without value, this is my current struct :</p> <pre><code>// Campaign represents a email campaign type Campaign struct { ID bson.ObjectId `json:"id" bson:"_id"` CampaignName string `json:"campaign_name" bson:"campaign_name"` FromName []string `json:"from_name" bson:"from_name"` FromEmail string `json:"from_email" bson:"from_email"` ReplyEmail string `json:"reply_email" bson:"reply_email"` Subject []string `json:"subject" bson:"subject"` BodyText string `json:"body_text" bson:"body_text"` BodyHTML string `json:"body_html" bson:"body_html"` SMTPList bson.ObjectId `json:"smtp_list" bson:"smtp_list"` EmailList bson.ObjectId `json:"email_list" bson:"email_list"` DateCreated time.Time `json:"date_created" bson:"date_created"` DateUpdated time.Time `json:"date_updated" bson:"date_updated"` DateSendFinish time.Time `json:"date_send_finish" bson:"date_send_finish"` OwnerID bson.ObjectId `json:"owner_id" bson:"owner_id"` Opens int `json:"opens" bson:"opens"` Clicks int `json:"clicks" bson:"clicks"` Status string `json:"status" bson:"status"` } </code></pre> <p>I want to return Status = "draft" How i can do this ?</p> </div>

2019 AI开发者大会

2019 AI开发者大会(AI ProCon 2019)是由中国IT社区CSDN主办的AI技术与产业年度盛会。多年经验淬炼,如今蓄势待发:2019年9月6-7日,大会将有近百位中美顶尖AI专家、知名企业代表以及千余名AI开发者齐聚北京,进行技术解读和产业论证。我们不空谈口号,只谈技术,诚挚邀请AI业内人士一起共铸人工智能新篇章!


实验内容: 通过对具体的文件存储空间的管理、文件的物理结构、目录结构和文件操作的实现,加深对文件系统内部功能和实现过程的理解。 要求: 1.在内存中开辟一个虚拟磁盘空间作为文件存储器,在其上实现一个简



2019数学建模A题高压油管的压力控制 省一论文即代码




Git 实用技巧

这几年越来越多的开发团队使用了Git,掌握Git的使用已经越来越重要,已经是一个开发者必备的一项技能;但很多人在刚开始学习Git的时候会遇到很多疑问,比如之前使用过SVN的开发者想不通Git提交代码为什么需要先commit然后再去push,而不是一条命令一次性搞定; 更多的开发者对Git已经入门,不过在遇到一些代码冲突、需要恢复Git代码时候就不知所措,这个时候哪些对 Git掌握得比较好的少数人,就像团队中的神一样,在队友遇到 Git 相关的问题的时候用各种流利的操作来帮助队友于水火。 我去年刚加入新团队,发现一些同事对Git的常规操作没太大问题,但对Git的理解还是比较生疏,比如说分支和分支之间的关联关系、合并代码时候的冲突解决、提交代码前未拉取新代码导致冲突问题的处理等,我在协助处理这些问题的时候也记录各种问题的解决办法,希望整理后通过教程帮助到更多对Git操作进阶的开发者。 本期教程学习方法分为“掌握基础——稳步进阶——熟悉协作”三个层次。从掌握基础的 Git的推送和拉取开始,以案例进行演示,分析每一个步骤的操作方式和原理,从理解Git 工具的操作到学会代码存储结构、演示不同场景下Git遇到问题的不同处理方案。循序渐进让同学们掌握Git工具在团队协作中的整体协作流程。 在教程中会通过大量案例进行分析,案例会模拟在工作中遇到的问题,从最基础的代码提交和拉取、代码冲突解决、代码仓库的数据维护、Git服务端搭建等。为了让同学们容易理解,对Git简单易懂,文章中详细记录了详细的操作步骤,提供大量演示截图和解析。在教程的最后部分,会从提升团队整体效率的角度对Git工具进行讲解,包括规范操作、Gitlab的搭建、钩子事件的应用等。 为了让同学们可以利用碎片化时间来灵活学习,在教程文章中大程度降低了上下文的依赖,让大家可以在工作之余进行学习与实战,并同时掌握里面涉及的Git不常见操作的相关知识,理解Git工具在工作遇到的问题解决思路和方法,相信一定会对大家的前端技能进阶大有帮助。


原价169,限时立减100元! 系统掌握Python核心语法16点,轻松应对工作中80%以上的Python使用场景! 69元=72讲+源码+社群答疑+讲师社群分享会&nbsp; 【哪些人适合学习这门课程?】 1)大学生,平时只学习了Python理论,并未接触Python实战问题; 2)对Python实用技能掌握薄弱的人,自动化、爬虫、数据分析能让你快速提高工作效率; 3)想学习新技术,如:人工智能、机器学习、深度学习等,这门课程是你的必修课程; 4)想修炼更好的编程内功,优秀的工程师肯定不能只会一门语言,Python语言功能强大、使用高效、简单易学。 【超实用技能】 从零开始 自动生成工作周报 职场升级 豆瓣电影数据爬取 实用案例 奥运冠军数据分析 自动化办公:通过Python自动化分析Excel数据并自动操作Word文档,最终获得一份基于Excel表格的数据分析报告。 豆瓣电影爬虫:通过Python自动爬取豆瓣电影信息并将电影图片保存到本地。 奥运会数据分析实战 简介:通过Python分析120年间奥运会的数据,从不同角度入手分析,从而得出一些有趣的结论。 【超人气老师】 二两 中国人工智能协会高级会员 生成对抗神经网络研究者 《深入浅出生成对抗网络:原理剖析与TensorFlow实现》一书作者 阿里云大学云学院导师 前大型游戏公司后端工程师 【超丰富实用案例】 0)图片背景去除案例 1)自动生成工作周报案例 2)豆瓣电影数据爬取案例 3)奥运会数据分析案例 4)自动处理邮件案例 5)github信息爬取/更新提醒案例 6)B站百大UP信息爬取与分析案例 7)构建自己的论文网站案例


深度学习系列课程从深度学习基础知识点开始讲解一步步进入神经网络的世界再到卷积和递归神经网络,详解各大经典网络架构。实战部分选择当下最火爆深度学习框架PyTorch与Tensorflow/Keras,全程实战演示框架核心使用与建模方法。项目实战部分选择计算机视觉与自然语言处理领域经典项目,从零开始详解算法原理,debug模式逐行代码解读。适合准备就业和转行的同学们加入学习! 建议按照下列课程顺序来进行学习 (1)掌握深度学习必备经典网络架构 (2)深度框架实战方法 (3)计算机视觉与自然语言处理项目实战。(按照课程排列顺序即可)


一 专题从基础的C语言核心到c++ 和stl完成基础强化; 二 再到数据结构,设计模式完成专业计算机技能强化; 三 通过跨平台网络编程,linux编程,qt界面编程,mfc编程,windows编程,c++与lua联合编程来完成应用强化 四 最后通过基于ffmpeg的音视频播放器,直播推流,屏幕录像,




文章目录Java概述何为编程什么是Javajdk1.5之后的三大版本JVM、JRE和JDK的关系什么是跨平台性?原理是什么Java语言有哪些特点什么是字节码?采用字节码的最大好处是什么什么是Java程序的主类?应用程序和小程序的主类有何不同?Java应用程序与小程序之间有那些差别?Java和C++的区别Oracle JDK 和 OpenJDK 的对比基础语法数据类型Java有哪些数据类型switc...



Vue.js 2.0之全家桶系列视频课程

基于新的Vue.js 2.3版本, 目前新全的Vue.js教学视频,让你少走弯路,直达技术前沿! 1. 包含Vue.js全家桶(vue.js、vue-router、axios、vuex、vue-cli、webpack、ElementUI等) 2. 采用笔记+代码案例的形式讲解,通俗易懂




第三十一问: 说一下线程中sleep()和wait()区别? 1 . sleep()是让正在执行的线程主动让出CPU,当时间到了,在回到自己的线程让程序运行。但是它并没有释放同步资源锁只是让出。 2.wait()是让当前线程暂时退让出同步资源锁,让其他线程来获取到这个同步资源在调用notify()方法,才会让其解除wait状态,再次参与抢资源。 3. sleep()方法可以在任何地方使用,而wait()只能在同步方法或同步块使用。 ...

java jdk 8 帮助文档 中文 文档 chm 谷歌翻译

JDK1.8 API 中文谷歌翻译版 java帮助文档 JDK API java 帮助文档 谷歌翻译 JDK1.8 API 中文 谷歌翻译版 java帮助文档 Java最新帮助文档 本帮助文档是使用谷





Visual Assist X 破解补丁

vs a's'sixt插件 支持vs2008-vs2019 亲测可以破解,希望可以帮助到大家


【为什么学爬虫?】 &nbsp; &nbsp; &nbsp; &nbsp;1、爬虫入手容易,但是深入较难,如何写出高效率的爬虫,如何写出灵活性高可扩展的爬虫都是一项技术活。另外在爬虫过程中,经常容易遇到被反爬虫,比如字体反爬、IP识别、验证码等,如何层层攻克难点拿到想要的数据,这门课程,你都能学到! &nbsp; &nbsp; &nbsp; &nbsp;2、如果是作为一个其他行业的开发者,比如app开发,web开发,学习爬虫能让你加强对技术的认知,能够开发出更加安全的软件和网站 【课程设计】 一个完整的爬虫程序,无论大小,总体来说可以分成三个步骤,分别是: 网络请求:模拟浏览器的行为从网上抓取数据。 数据解析:将请求下来的数据进行过滤,提取我们想要的数据。 数据存储:将提取到的数据存储到硬盘或者内存中。比如用mysql数据库或者redis等。 那么本课程也是按照这几个步骤循序渐进的进行讲解,带领学生完整的掌握每个步骤的技术。另外,因为爬虫的多样性,在爬取的过程中可能会发生被反爬、效率低下等。因此我们又增加了两个章节用来提高爬虫程序的灵活性,分别是: 爬虫进阶:包括IP代理,多线程爬虫,图形验证码识别、JS加密解密、动态网页爬虫、字体反爬识别等。 Scrapy和分布式爬虫:Scrapy框架、Scrapy-redis组件、分布式爬虫等。 通过爬虫进阶的知识点我们能应付大量的反爬网站,而Scrapy框架作为一个专业的爬虫框架,使用他可以快速提高我们编写爬虫程序的效率和速度。另外如果一台机器不能满足你的需求,我们可以用分布式爬虫让多台机器帮助你快速爬取数据。 &nbsp; 从基础爬虫到商业化应用爬虫,本套课程满足您的所有需求! 【课程服务】 专属付费社群+每周三讨论会+1v1答疑


功能描述:包括用户的登录注册,以及个人资料的修改.商品的分类展示,详情,加入购物车,生成订单,到银行支付等!另外还有收货地址的和我的收藏等常用操作.环境(JDK 1.7 ,mysql 5.5,Ecli


&nbsp; &nbsp; &nbsp; &nbsp; 本课程为Python数据挖掘方向的入门课程,课程主要以真实数据为基础,详细介绍数据挖掘入门的流程和使用Python实现pandas与numpy在数据挖掘方向的运用,并深入学习如何运用scikit-learn调用常用的数据挖掘算法解决数据挖掘问题,为进一步深入学习数据挖掘打下扎实的基础。


图像处理和计算机视觉的课程大家已经看过很多,但总有“听不透”,“用不了”的感觉。课程致力于创建人人都能听的懂的计算机视觉,通过生动、细腻的讲解配合实战演练,让学生真正学懂、用会。 【超实用课程内容】 课程内容分为三篇,包括视觉系统构成,图像处理基础,特征提取与描述,运动跟踪,位姿估计,三维重构等内容。课程理论与实战结合,注重教学内容的可视化和工程实践,为人工智能视觉研发及算法工程师等相关高薪职位就业打下坚实基础。 【课程如何观看?】 PC端: 移动端:CSDN 学院APP(注意不是CSDN APP哦) 本课程为录播课,课程2年有效观看时长,但是大家可以抓紧时间学习后一起讨论哦~ 【学员专享增值服务】 源码开放 课件、课程案例代码完全开放给你,你可以根据所学知识,自行修改、优化 下载方式:电脑登录,点击右下方课程资料、代码、课件等打包下载


本课程内容系统、全面、简洁、通俗易懂,通过2个多小时的介绍,让大家对软件测试有个系统的理解和认识,具备基本的软件测试理论基础。 主要内容分为5个部分: 1 软件测试概述,了解测试是什么、测试的对象、原则、流程、方法、模型;&nbsp; 2.常用的黑盒测试用例设计方法及示例演示;&nbsp; 3 常用白盒测试用例设计方法及示例演示;&nbsp; 4.自动化测试优缺点、使用范围及示例‘;&nbsp; 5.测试经验谈。


课程主要面向嵌入式Linux初学者、工程师、学生 主要从一下几方面进行讲解: 1.linux学习路线、基本命令、高级命令、vi及vim入门讲解 3.软件安装下载、NFS、Samba、FTP等服务器配置及使用

2019 Python开发者日-培训


快速入门Android开发 视频 教程 android studio

这是一门快速入门Android开发课程,顾名思义是让大家能快速入门Android开发。 学完能让你学会如下知识点: Android的发展历程 搭建Java开发环境 搭建Android开发环境 Android Studio基础使用方法 Android Studio创建项目 项目运行到模拟器 项目运行到真实手机 Android中常用控件 排查开发中的错误 Android中请求网络 常用Android开发命令 快速入门Gradle构建系统 项目实战:看美图 常用Android Studio使用技巧 项目签名打包 如何上架市场




这是一个门针对零基础学员学习微信小程序开发的视频教学课程。课程采用腾讯官方文档作为教程的唯一技术资料来源。杜绝网络上质量良莠不齐的资料给学员学习带来的障碍。 视频课程按照开发工具的下载、安装、使用、程序结构、视图层、逻辑层、微信小程序等几个部分组织课程,详细讲解整个小程序的开发过程

相关热词 c# dbml文件 修改 c#遍历tree c# 能够控制单片机 c#对象写入数据库 c# 添加activex c#2005 json c# 数据库在云端 c# 字符串移位加密 c#禁用滚轮 c#实体类list去重复