go mongo aggregate cond

db.devices.aggregate({
$match: {userId: "v73TuQqZykbxFXsWo", state: true}},
{
  $project: {
    userId: 1,
    categorySlug: 1,
    weight: { 
      $cond: [ 
        {"$or": [  
          {$eq: ["$categorySlug", "air_fryer"] }, 
          {$eq: ["$categorySlug", "iron"] } 
        ] }, 
      0, 1] } 
    } },  
    {$sort: {weight: 1}},
    { $limit : 10 }
);

 

 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})
db.gmsNews.aggregate([
  {
     $match:{source:"..."}
  },
  {
     $unwind: "$comments"
  },
  {
     $group: {
        _id: "$url",
        size: {
           $sum: 1
        },
     }
  },
  {
     $sort : { size : -1 } 
  },
  { 
     $limit : 5
  }
])

 

o1 := bson.M{
        "$match" :bson.M {"source":"..."},
}

o2 := bson.M{
    "$unwind": "$comments",
}

o3 := bson.M{
    "$group": bson.M{
        "_id": "$url",
        "size": bson.M{
            "$sum": 1,
        },
    },
}

o4 := bson.M{
    "sort": bson.M{
        "size": -1,
    },
}

o5 := bson.M{
    "$limit": 5,
}

operations := []bson.M{o1, o2, o3, o4, o5}

pipe := c.Pipe(operations)

// Run the queries and capture the results
results := []bson.M{}
err1 := pipe.All(&results)

if err1 != nil {
    fmt.Printf("ERROR : %s\n", err1.Error())
    return
}

fmt.Printf("URL : %s, Size: %sn", results[0]["_id"], results[0]["size"])

operations := []bson.M{o1, o2, o3, o4, o5}  注意的顺序

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值