MongoDB
 sql >> Base de Dados >  >> NoSQL >> MongoDB

consulta de agregação mongo com driver mgo


Os exemplos nos documentos seriam suficientes para começar. No entanto, se você não estiver familiarizado com golang, o $cond parte pode ser um pouco complicado. Veja abaixo o código de exemplo:
coleção
    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})

Veja também mgo:type Pipe