MongoDB – How to query a MongoDB Collection (Part II)

By | 18/05/2022

MongoDB – How to query a MongoDB Collection (Part I)


LIKE OPERATOR – ‘NNN%’

// select all users where _id like '61fefc%'
db.users.find({"_id":/^61fefc/})

LIKE OPERATOR – ‘%NNN’

// select all users where name like '%er'
db.users.find({"name":/er$/})


LIKE OPERATOR – ‘%NNN%’

// select all users where name like '%ED%'
db.users.find({"company":/ED/})


AND WITH OR

// select all users where age <=34 and (isActive = false or gender='female')
db.users.find(
    {
        age: {$lte:34},
        $or:
        [
            {isActive: false},
            {gender: 'female'}
        ]
    }    
)


IN

// select all users where isActive = false and age in (33,34)
db.users.find(
    {
        isActive:false,
        age: {$in: [33,34]}
    }
)


GROUP BY

// select gender, Sum(age), AVG(age) from users where gender="male")
// group by gender having count>=1 order by gender
db.users.aggregate(
    [
        {$match:{ gender: "male"}},
        {$group: { _id: "$gender", TotalAge: {$sum: "$age"},AvgAge: {$avg: "$age"}, CountRow: {$sum: 1}}},
        {$match: {CountRow: {$gte: 1}}},
        {$sort: {_id: 1}},
        {$project: { _id: 1, TotalAge: 1, AvgAge: 1, CountRow:1  }}
    ]    
)



Leave a Reply

Your email address will not be published.