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可以类比着操作
综上,可能不清晰,望各位看官包涵