sql >> Base de Datos >  >> NoSQL >> MongoDB

consulta de agregación mongo con controlador mgo

Los ejemplos en los documentos serían suficientes para comenzar. Sin embargo, si no está familiarizado con golang, el $cond parte podría ser un poco complicado. Vea a continuación el código de ejemplo:

    collection := session.DB("dbName").C("devices")

    stage_match := bson.M{"$match":bson.M{"userId":"v73TuQqZykbxFXsWo", "state": true}}

    condition_weight := []interface{}{bson.M{"$or": []bson.M{
                       bson.M{"$eq": []string{"$categorySlug", "air_fryer"}},
                       bson.M{"$eq": []string{"$categorySlug", "iron"}},
    }}, 0, 1}

    stage_project:= bson.M{"$project": bson.M{"userId":1, "categorySlug":1, "weight": condition_weight}}

    stage_sort := bson.M{"$sort": bson.M{"weight":1}}

    stage_limit := bson.M{"$limit": 10}

    pipe := collection.Pipe([]bson.M{stage_match, stage_project, stage_sort, stage_limit})

Ver también mgo:type Pipe