06 MongoDB Queries
06 MongoDB Queries
06 MongoDB Queries
Operators
$lt $gt
Equality Query
๏ Match by field name and it's exact value
{<fieldName1> : <value1>, <fieldName2> : <value2>, ...}
๏ Examples
{"name" : "Kitty Snow"}
{"age" : 38}
{"gender" : "female" , "eyeColor" : "blue"}
AND Condition
Operators
๏ Operators add conditions
{ <fieldName1>: { <operator1>: <value1> }, ... }
๏ Examples
{"favoriteFruit" : {"$ne": "apple"}}
{"age" : {"$gt": 25}}
{"eyeColor" : {"$in": ["green" , "blue"]}}
Comparison Operators
$in $nin
๏ Examples
{"eyeColor" : {"$in": ["green" , "blue"]}}
{"favoriteFruit" : {"$nin": ["banana" , "apple"]}}
$and
Note
≠
{"age": {"$ne": 25} , "age": {"$gte": 20}}
$or
๏ Examples
{ $or: [ { "gender" : "male" }, { "age" : 25 } ] }
{ $or: [ { "age" : 20 }, { "age" : 27 }] }
๏ Examples
{ "company.title": "SHEPARD" }
{ "company.location.address": "379 Tabor Court"}
Query Array by element Value
๏ Examples
{ tags: "ad" }
{ "tags.0": "ad"}
{ "tags.3": "ab"}
Query Array using $all , $size
๏ Examples
{ tags: {"$all": ["ad" , "eu"]}}
{ tags: {"$size": 4}}
Query Array of Nested Documents
{
"friends": [
{
"name": "Lora",
"age": NumberInt(23)
},
{
"name": "Bob",
"age": NumberInt(25)
}
]
}
๏ Examples
{ "friends.name": "Lora" }
{ friends: {"name": "Lora", "age": 23} }
$elemMatch
๏ At least one nested document in the Array must match ALL
conditions. Order of conditions doesn't matter
{ <arrayField>: { $elemMatch: { <condition1> , <condition2> , ...}} }
๏ Examples
{ friends: { $elemMatch: { name:
"Bob", registered: false }}}
{ friends: { $elemMatch: { registered:
false, age: 25 }}}
Element Operators
$exists $type
๏ Examples
{ tags: { $exists: true}}
{ name: { $exists: false}}
๏ Examples
{ city: {"$regex": /ton/i}}
{ tags: {"$regex": /^ad$/ , $options: "i"}}
{ state: {"$regex": "ca"}}
SUMMARY
๏ Query Operators
$or
$and
$regex
$lt, $gt
๏ Array Query Operators
$all
$size
$elemMatch