Querying MongoDB

2 ways to view the entire contents of collection

db.getCollection("friendsCollection").find()

db.friendsCollection.find()

Filter Documents

// exact match

db.friendsCollection.find(
{
    age: 31
}
)

// less than

db.friendsCollection.find(
{
    age : {$lt : 31}
}
)

// greater than

db.friendsCollection.find(
{
    age : {$gt : 30}
}
)

// Between

db.friendsCollection.find(
{
    age : {$gt : 29},
    age : {$lt : 31}
}
)

// nested

db.friendsCollection.find({"name.firstname":"Ben"});

More Queries

Using Regular Expression

Regular expressions are used within two slashes / /

// Find firstnames containing letter R

db.friendsCollection.find({"firstname": /.*R.*/})
or
db.friendsCollection.find({"firstname": /R/})
// Find names starting with lower case r

db.friendsCollection.find({"firstname": /^r/})

// Find names ending with e

db.friendsCollection.find({"firstname": /e$/})

// case insensitive

db.friendsCollection.find({"firstname":{'$regex' : '^r', '$options' : 'i'}})

db.friendsCollection.find({"firstname":{"$regex" : "^r", "$options" : "i"}})

Last updated