Find by _id with pymongo howto do that ?

23 views
Skip to first unread message

bussiere adrien

unread,
Dec 20, 2016, 9:32:00 AM12/20/16
to mgo-users
I have some difficulties to find data 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?



Reply all
Reply to author
Forward
0 new messages