Go MongoDB驱动程序忽略数据更新

时间:2019-11-11 09:16:53

标签: mongodb go

我有一个这样的文件

{
    "name": "nnn",
    "age": 21,
    "status": false
}

我想获得status的价值:

    client, err := mongo.NewClient(options.Client().ApplyURI(DbURI))
    if err != nil {
        return nil, err
    }

    err = client.Connect(ctx)
    if err != nil {
        return nil, err
    }

    err = client.Ping(ctx, nil)
    if err != nil {
        return nil, err
    }

    database := client.Database(DbName)
    if database == nil {
        return nil, err
    }

    collection := database.Collection(CollectionName)
    if collection == nil {
        return false, err
    }

    pipeline := []bson.M{
        {"$match": bson.M{
            "name": "nnnn",
        }},
        {"$project": bson.M{
            "_id":    0,
            "status": 1,
        }},
    }

    opts := options.Aggregate()
    cursor, err := collection.Aggregate(ctx, pipeline, opts)
    if err != nil {
        return false, err
    }

    var res []struct {
        Status bool   `bson:"status"`
    }

    if err := cursor.All(ctx, &res); err != nil {
        return false, err
    }

    return res[0].Status, nil
}

如果我更改statusMongoDB Compass字段的值并运行此代码,则会得到一个旧值。如果我在mongo shell中获得了价值,那么我得到了正确的价值

db.users.aggregate([{
    $match: {
        "name": "nnn"
    }
}, {
    $project: {
        _id: 0,
        status: 1
    }
}]).pretty()

如果我将字段添加到res或将其删除,我会在go中获得正确的值

    var res []struct {
        Status bool   `bson:"status"`
        Age int `bson:"age"`
    }

为什么会这样?更改后,如何管理与mongo的连接以立即获取更新?

0 个答案:

没有答案