mongodb使用$switch做条件处理

本文介绍了如何在MongoDB中利用$switch进行条件判断处理,特别是针对cited_by字段,无论是数组还是单个对象,都能灵活应用$switch进行操作。示例中展示了从数组中提取最大值并根据条件返回不同结果的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

mongodb使用$switch做条件处理:

''''var userAccess = [ "Book", "Journal article", "Conference paper"];
db.all1000.aggregate([
    {
        $project:{
            "three_type": 1, //想要保留的字段(three_type)
            "citation":      //想要保留的字段2(是对字段(cited_by)进行分类后生成的新字段)      
	{
	  $switch: {             //类似if-else if-esle的分类器
		   branches: [
				{
				  case: { $and : [ { $gte : [ { $max : "$cited_by" }, 0 ] },
								   { $lte : [ { $max : "$cited_by" }, 10 ] } ] }, //条件1
				  then: "1"                                               //对应的结果
				},
				{
				  case: { $and : [ { $gt : [ { $max : "$cited_by" }, 10 ] },
								   { $lte : [ { $max : "$cited_by" }, 50 ] } ] },
				  then: "2"
				},
				 {
				  case: { $and : [ { $gt : [ { $max : "$cited_by" }, 50 ] },
								   { $lte : [ { $max : "$cited_by" }, 100 ] } ] },
				  then: "3"
				},
											{
				  case: { $and : [ { $gt : [ { $max : "$cited_by" }, 100 ] },
								   { $lte : [ { $max : "$cited_by" }, 500 ] } ] },
				  then: "4"
				},
				  {
				  case: { $and : [ { $gt : [ { $max : "$cited_by" }, 500 ] },
								   { $lte : [ { $max : "$cited_by" }, 2000 ] } ] },
				  then: "5"
				},
                                          {
                                  case: { $gt : [ { $max : "$cited_by" }, 2000 ] },
                                  then: "6"
                                }
			  ],
			  default: "No found."       //作用类似于else
			}
		}


            }
        },    
    {
        $group : { //分组
            _id :{type: "$three_type", citation: "$citation"}, //根据字段分组(字段内容相同为一组)
            count:{ $sum: 1 }                         
     } 
     }
]
)'''

以上中cited_by字段内容可以为数组,举例:

cited_by:[1,3,5]

上面$max作用可以提取出其中的最大值5,然后对其进行条件判断,其结果为then后面的内容
以上中cited_by字段内容可以为单个对象,我们可以这修改第一个case的代码为:

{
				  case: { $and : [ { $gte : [ "$cited_by", 0 ] },
								   { $lte : [ "$cited_by", 10 ] } ] },
				  then: "1"
				}

以下的case可以类比着操作
综上,可能不清晰,望各位看官包涵

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值