【发布时间】:2018-12-11 07:49:52
【问题描述】:
在 mongodb 中有一个用户数据已存储在集合 challange 中,数据如下所示:
{
"_id" : 1,
"name" : "puneet",
"last" : "jindal",
"email" : "puneet@g.com"
}
{
"_id" : ObjectId("5b3af82cdb3aaa47792b5fd3"),
"name" : "hardeep",
"last" : "singh",
"email" : "hardeep@g.com"
}
{
"_id" : 3,
"name" : "gaurav",
"last" : "bansal",
"email" : "gaurav@g.com"
}
{
"_id" : ObjectId("5b3af87ddb3aaa47792b5fd4"),
"name" : "manish",
"last" : "jindal",
"email" : "manish@g.com"
}
在上面的数据中,有四个记录,其中两个具有整数形式的 id,另一个具有对象形式的 id。我只想检索在 id 字段中具有object id 的所有记录。谁能告诉我应该在代码中编写什么查询,只检索具有对象 id 的记录。
更新:
我正在使用的代码:
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(&result)
if err != nil {
return result, err
}
return result, nil
}
conditions := bson.M{'_id': bson.M{'$type': "objectId" } }
data, err := models.GetAllUsers(conditions)
我使用这个遇到的错误:-
controllers/UserController.go:18:23: 无效字符文字(超过一个字符) controllers/UserController.go:18:28: 不能使用 '\u0000' (type rune) 作为映射键中的类型字符串
【问题讨论】:
-
没有。我从来没有使用过 MongoDB。我不知道您为什么认为改进格式的人会成为您特定问题的主题专家。但你已经有多个答案了。
-
@flimzy 如果我们在 mongodb shell 中运行它,这些答案是正确的,但我需要它作为 golang 中的查询
标签: mongodb go mongodb-query mgo