Nov 26, 2015

if/else condition in MongoDB

$cond operator has keyword "if", "then" and "else", using this operator we can perform if/else in MongoDb query.
See following example:


Use Test



db.Users.insert(
{
    "fName" : "Dilip",
    "lName" : "Singh",
    "address" : "Noida",
    "totalOrder" : 150,
    "createdDate" : "2014/07/07"
})
db.Users.insert(
{
    "fName" : "Vipul",
    "lName" : "Bhatt",
    "address" : "Delhi",
    "totalOrder" : 50,
    "createdDate" : "2013/07/07"
})
db.Users.insert(
{
    "fName" : "Brijesh",
    "lName" : "Kumar",
    "address" : "Gorakhpur",
    "totalOrder" : 70,
    "createdDate" : "2012/07/07"
})
db.Users.insert(
{
    "fName" : "Raj",
    "lName" : "Kumar",
    "address" : "Bokaro",
    "totalOrder" : 40,
    "createdDate" : "2010/07/07"
})

db.Users.find()


Output


/* 0 */
{
    "_id" : ObjectId("55dac0b31c949abf34d5daed"),
    "fName" : "Dilip",
    "lName" : "Singh",
    "address" : "Noida",
    "totalOrder" : 150,
    "createdDate" : "2014/07/07"
}

/* 1 */
{
    "_id" : ObjectId("55dac0c21c949abf34d5daf1"),
    "fName" : "Vipul",
    "lName" : "Bhatt",
    "address" : "Delhi",
    "totalOrder" : 50,
    "createdDate" : "2013/07/07"
}

/* 2 */
{
    "_id" : ObjectId("55dac0d11c949abf34d5daf2"),
    "fName" : "Brijesh",
    "lName" : "Kumar",
    "address" : "Gorakhpur",
    "totalOrder" : 70,
    "createdDate" : "2012/07/07"
}

/* 3 */
{
    "_id" : ObjectId("55dac0e31c949abf34d5daf3"),
    "fName" : "Raj",
    "lName" : "Kumar",
    "address" : "Bokaro",
    "totalOrder" : 40,
    "createdDate" : "2010/07/07"
}


Now we are apply query if user has totalOrder more  than 100 so his User Type will be  Gold else Silver. See following query.


db.Users.aggregate(
[{
    $project :
    {
        fName:1,
        totalOrder:1,
        UserType:{
            $cond:{
                    if:{$gte:["$totalOrder",100]},
                    then:"gold",
                    else:"Silver"
                 }
                }
    }
}])


Output


/* 0 */
{
    "result" : [
        {
            "_id" : ObjectId("55dac0b31c949abf34d5daed"),
            "fName" : "Dilip",
            "totalOrder" : 150,
            "UserType" : "gold"
        },
        {
            "_id" : ObjectId("55dac0c21c949abf34d5daf1"),
            "fName" : "Vipul",
            "totalOrder" : 50,
            "UserType" : "Silver"
        },
        {
            "_id" : ObjectId("55dac0d11c949abf34d5daf2"),
            "fName" : "Brijesh",
            "totalOrder" : 70,
            "UserType" : "Silver"
        },
        {
            "_id" : ObjectId("55dac0e31c949abf34d5daf3"),
            "fName" : "Raj",
            "totalOrder" : 40,
            "UserType" : "Silver"
        }
    ],
    "ok" : 1
}