使用mgo按id查找

huangapple go评论76阅读模式
英文:

Find by id with mgo

问题

我想通过_id查找数据。我知道这个数据存在,而且这个_id也存在(我已经用pymongo测试过)。

但是下面的代码找不到它:

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
}

它只返回一个0

但是我可以使用pytmongo和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)

以下是结果:

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

有人有任何想法吗?

编辑:
我尝试了以下代码:

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

但是我仍然得到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
英文:

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

答案1

得分: 16

你可以使用Collection.FindId(),然后只传递id值,或者使用Collection.Find(),然后需要指定字段名和值:

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

// 或者
err2 := c.Find(bson.M{"_id": bson.ObjectIdHex("58593d1d6aace357b32bb3a1")}).
    One(&data)

如果没有错误,那就表示找到了文档。

如果你总是看到打印出来的值是0(作为id_cookie.IdCookie字段的值),那就表示文档中保存这个id的字段名不同。

使用结构体标签来告诉它在MongoDB中是如何存储的。例如,如果在你的MongoDB中它被称为"myid",你可以这样映射它:

type id_cookie struct {
    IdCookie int `bson:"myid"`
}

还要注意的是,你不应该每次查询数据时都连接到MongoDB服务器,而是连接一次,然后重复使用会话。详细信息请参考:链接

英文:

You either use Collection.FindId() and then you pass only the id value, or you use Collection.Find() and then you have to specify a value with the field name too:

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

// OR
err2 := c.Find(bson.M{"_id": bson.ObjectIdHex("58593d1d6aace357b32bb3a1")}).
    One(&data)

If you get no errors, that means the document is found.

If you always see 0 printed (as the value of the id_cookie.IdCookie field), that means the field in the document holding this id has a different name.

Use struct tags to tell how it is stored in your MongoDB. E.g. if in your MongoDB it is called "myid", you can map it like this:

type id_cookie struct {
    IdCookie int `bson:"myid"`
}

Also note that you should not connect to the MongoDB server every time you want to query some data, instead connect once, and just reuse the session. for details see: https://stackoverflow.com/questions/40999637/mgo-query-performance-seems-consistently-slow-500-650ms/41000876#41000876

huangapple
  • 本文由 发表于 2016年12月20日 21:56:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/41244024.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定