如何获取 mongodb 中具有对象 ID 的所有记录

How to get all the records in mongodb having object id

在 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: invalid character literal (more than one character) controllers/UserController.go:18:28: cannot use '\u0000' (type rune) as type string in map key

您可以使用 $type 运算符:

db.challenge.find({ _id: { $type: "objectId" } })

您可以像下面这样尝试

//For Retrieving for ObjectID
db.challange.find(
    {
        "_id": {
            $type: 7  //ObjectID
        }
    }
)

//For Retrieving for Number
db.challange.find(
    {
        $or: [
            {
                "_id": {
                    $type: 1  //double
                }
            },
            {
                "_id": {
                    $type: 16  //32 bit integer
                }
            },
            {
                "_id": {
                    $type: 18  //64 bit integer
                }
            },
            {
                "_id": {
                    $type: 19  //decimal
                }
            }
        ]
    }
)

参考$type , $or

'_id''$type'是无效的rune literals,你不能在一个符文文字中列出多个符文(字符)(只能是一个符文)。

bson.M type is a map with string key type, so you have to use string literals(或表达式),像这样:

conditions := bson.M{"_id": bson.M{"$type": "objectId"}}

另请注意,bson package holds constants 用于不同的类型,因此使用这些常量更安全:

conditions := bson.M{"_id": bson.M{"$type": bson.ElementObjectId}}