My data structure like this: Blog: id string title string content string comments: id string content string And if I want to get a comment with id:000000000000 in blog with id:1111111111111, I tried: ses.DB("db").C("Blog").Find(bson.M{"comments.id":"1111111111111"}).All(&res) got expected result then try: ses.DB("db").C("Blog").Find(bson.M{"id":"000000000000"}).All(&res) got expected result And then ses.DB("db").C("Blog").Find(bson.M{"id":"000000000000","comments.id": "1111111111111"}).All(&res) got nothing
res := mgd.ExcuteQuery(collection, query)
.
//mgd.go
package mgd
import (
"labix.org/v2/mgo"
)
var (
mgoSession *mgo.Session
databaseName = "TestDB"
)
func cloneSession(method string) *mgo.Session {
if mgoSession == nil {
var err error
mgoSession, err = mgo.Dial("localhost")
if err != nil {
panic("Can't use 'Dial('localhost')' connect to mongodb")
}
}
return mgoSession.Clone()
}
func ExcuteQuery(collection string, query interface{}) []interface{} {
ses := cloneSession("ExcuteQuery")
defer ses.Close()
var result []interface{}
err := ses.DB(databaseName).C(collection).Find(query).All(&result)
if err != nil {
panic(err)
}
return result
}
func ExcuteInsert(collection string, model interface{}) {
ses := ensureMongoConnection("ExcuteInsert")
defer ses.Close()
err := ses.DB(databaseName).C(collection).Insert(model)
if err != nil {
panic(err)
}
}
//mgd_test.go
package mgd
import (
"aws/mgd"
. "labix.org/v2/mgo/bson"
. "launchpad.net/gocheck"
"testing"
)
func Test(t *testing.T) { TestingT(t) }
type MySuite struct {
Token string
Title string
Comments []Comment
}
type Comment struct {
Token string
Content string
}
var (
_ = Suite(&MySuite{})
collection = "test"
blogToken = "blog-0"
title = "how to make uml ..."
commentToken = "comment-0"
content = "You are..."
)
func (s *MySuite) TestInsert(c *C) {
mgd.ExcuteInsert(collection, MySuite{blogToken, title, []Comment{Comment{commentToken, content}}})
}
func (s *MySuite) TestGetModel(c *C) {
res := mgd.ExcuteQuery(collection, M{"Token": blogToken, "Comments.Token": commentToken})
c.Assert(len(res), Equals, 1)
//here len(res)==0,but if mgd.ExcuteQuery(nil)...,the len(res)==1