Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用MongoDB进行分页_Mongodb_Go - Fatal编程技术网

如何使用MongoDB进行分页

如何使用MongoDB进行分页,mongodb,go,Mongodb,Go,我需要对Go和MongoDB进行分页,我对这个问题非常失望,因为我从几周前就无法实现分页了!我不想使用“跳过”,因为它消耗了太多的资源 代码如下: var limit int64 = 20 var offset int64 = 40 findOptions0 := options.Find() findOptions0.SetLimit(offset) findOptions0.SetSort(bson.M{"_id": 1}) f

我需要对Go和MongoDB进行分页,我对这个问题非常失望,因为我从几周前就无法实现分页了!我不想使用“跳过”,因为它消耗了太多的资源

代码如下:

var limit int64 = 20
    var offset int64 = 40

    findOptions0 := options.Find()
    findOptions0.SetLimit(offset)
    findOptions0.SetSort(bson.M{"_id": 1})

    findOptions := options.Find()
    findOptions.SetLimit(limit)
    findOptions.SetSort(bson.M{"_id": 1})

    cursor0, err32 := collection.Find(context.Background(), bson.M{}, findOptions)
    if err32 != nil {
        return status.Errorf(codes.Internal, fmt.Sprintf("Unknown1 internal error: %v", err32))
    }

    for cursor0.Next(context.Background()) {
        err := cursor0.Decode(&data0)
        if err != nil {
            return status.Errorf(codes.Unavailable, fmt.Sprintf("Could not decode data of cursor0: %v", err))
        }

    }

    err := cursor0.Decode(&data0)
    if err != nil {
        return status.Errorf(codes.Unavailable, fmt.Sprintf("Could not decode data of cursor0: %v", err))
    }

    cursor, err34 := collection.Find(context.Background(), bson.M{"_id": bson.M{"$gt": data0.ID}}, findOptions)
    if err34 != nil {
        log.Printf("lastID: ", data0.ID)
        return status.Errorf(codes.Internal, fmt.Sprintf("Unknown2 internal error: %v", err34))
    }
    

    for cursor.Next(context.Background()) {
        log.Printf("result: ", cursor)

        // Decode the data at the current pointer and write it to data
        err := cursor.Decode(data)
        // check error
        if err != nil {
            return status.Errorf(codes.Unavailable, fmt.Sprintf("Could not decode data: %v", err))
        }

        log.Printf("End of the for loop ")

对于“不太大”的偏移,使用“偏移”和“限制”只会稍微慢一点,所以在实践中它们就足够了。如果确实需要更好的性能,则必须获取、传输和设置查询的起始索引项。有关如何使用
mgo
,请参阅。官方驱动程序还支持设置初学者索引项,因此这在官方驱动程序中也是可行的。不确定您在这里期望什么。如果将偏移和限制作为输入,则必须使用skip AFAIK。为了避免这种情况,您需要首先更改API的输入。@icza官方驱动程序如何操作?你能告诉我吗?@Rachel Using@icza这是更好的方法吗:(或)FindOptions.SetMin()????哪一个最快?我们如何使用“newCursor”来获得下一组结果?