ans*_*nsh 0 go mongodb mongodb-query mgo
在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"
}
Run Code Online (Sandbox Code Playgroud)
在上面的数据中有四个记录,其中两个具有整数形式的id,而另一个具有对象形式的id.我只想检索object idid字段中的所有记录.任何人都可以告诉我应该在代码中写什么查询,只会检索具有对象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)
Run Code Online (Sandbox Code Playgroud)
我使用这个错误: -
controllers/UserController.go:18:23:无效字符文字(多个字符)控制器/ UserController.go:18:28:不能在地图键中使用'\ u0000'(类型符文)作为字符串
'_id'并且'$type'是无效的符文文字,你不能在符文文字中列出多个符文(字符)(只有一个符文).
该bson.M类型是与地图string密钥类型,所以你必须使用字符串文字(或表达式),就像这样:
conditions := bson.M{"_id": bson.M{"$type": "objectId"}}
Run Code Online (Sandbox Code Playgroud)
另请注意,bson包中包含不同类型的常量,因此使用这些常量更安全:
conditions := bson.M{"_id": bson.M{"$type": bson.ElementObjectId}}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
347 次 |
| 最近记录: |