聚合查询


这个地方比较复杂,详细参考我自己写的这个函数来

func MongoAggregate(collection string, pipeline interface{}, options ...*options.AggregateOptions) ([]interface{}, error) {
	//重连数据库
	DbReconnect()
	//获取collection对象
	coll := DB.Collection(collection)
	var cursor *mongo.Cursor
	var err error
	//获取cursor游标对象
	if len(options) > 0 {
		cursor, err = coll.Aggregate(ctx, pipeline, options[0])
	} else {
		cursor, err = coll.Aggregate(ctx, pipeline)
	}
	if err != nil {
		return nil, errors.New("查找数据失败")
	}
	//这里直接一次性获取所有数据,不在遍历避免资源消耗
	var test []interface{}
	err = cursor.All(ctx,&test)
	if err!=nil{
		return nil, errors.New("转换失败")
	}
	//转换成功,返回对应数据
	return test,nil
}

然后下面就是函数具体调用,注意参数哪里的顺序很重要,执行时会按照顺序来进行

match:=bson.M{"post_type":"post","status":"publish"}
result,err:=database.MongoConcatTable(database.CollArticle,database.CollArticleExtend,"post_id","extend",bson.M{"$match":match},bson.M{"$sort":bson.M{"post_id": -1}},bson.M{"$skip":int64(now)},bson.M{"$limit":pageNum})
	

文章作者: 小游
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 小游 !
  目录