Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

mongodb - Find by id with mgo

I would like to find a data by _id. I know that this data exists and that this _id exist (I've tested it with pymongo).

But the code below doesn't find it:

type id_cookie struct {
    IdCookie int
}

func get_id_mongo() int {
    session, err := mgo.Dial("127.0.0.1")
    if err != nil {
        panic(err)
    }
    defer session.Close()

    // Optional. Switch the session to a monotonic behavior.
    session.SetMode(mgo.Monotonic, true)

    c := session.DB("id_bag").C("id_cookie")
    data := id_cookie{}
    err2 := c.FindId(bson.M{"_id": bson.ObjectIdHex("58593d1d6aace357b32bb3a1")}).One(&data)
    if (err2 != nil){
        Info.Println("error")
        Info.Println(err2)
    }
    Info.Println(data)
    return data.IdCookie
}

It just returns me a 0.

But I can find it using pytmongo and python.

import requests
import pymongo 
from pymongo import MongoClient
from bson.objectid import ObjectId
from pprint import pprint
client = MongoClient('127.0.0.1', 27017)

import base64



db = client.id_bag
pprint(db.collection_names())
result = db.id_cookie.insert_one(
    { 'IdCookie': 1
    })
print(result.inserted_id)

data = db.id_cookie.find_one({"_id": ObjectId("58593d1d6aace357b32bb3a1")})
print(data)

here are the result :

['id_cookie', 'system.indexes']
58593d2d6aace357b32bb3a3
{'IdCookie': 1, '_id': ObjectId('58593d1d6aace357b32bb3a1')}

Does anyone have any idea?

Edit : i've try with :

err2 := c.FindId(bson.ObjectIdHex("58593d1d6aace357b32bb3a1")).One(&data)

but i still have 0 :

INFO: 2016/12/20 15:42:08 Cookie_Id.go:147: 1
INFO: 2016/12/20 15:42:08 Cookie_Id.go:149: 2
INFO: 2016/12/20 15:42:18 Cookie_Id.go:87: data
INFO: 2016/12/20 15:42:18 Cookie_Id.go:88: {0}
INFO: 2016/12/20 15:42:18 Cookie_Id.go:89: 0
INFO: 2016/12/20 15:42:18 Cookie_Id.go:118: 0
INFO: 2016/12/20 15:42:18 Cookie_Id.go:128: OK
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...