Mongodb Session 6
Mongodb Session 6
Behavior:
$expr can build query expressions that compare fields from the same
document in a $match stage.
If the $match stage is part of a $lookup stage, $expr can compare
fields using let variables. See Specify Multiple Join Conditions with
$lookup for an example.
$expr does not support multikey indexes.
Examples:
Compare Two Fields from A Single Document
Consider an monthlyBudget collection with the following documents:
{ "_id" : 1, "category" : "food", "budget": 400, "spent": 450 }
{ "_id" : 2, "category" : "drinks", "budget": 100, "spent": 150 }
{ "_id" : 3, "category" : "clothes", "budget": 100, "spent": 50 }
{ "_id" : 4, "category" : "misc", "budget": 500, "spent": 300 }
{ "_id" : 5, "category" : "travel", "budget": 200, "spent": 650 }
The following operation uses $expr to find documents where the
spent amount exceeds the budget:
db.monthlyBudget.find( { $expr: { $gt: [ "$spent" , "$budget" ] } } )
Result:
{ "_id" : 1, "category" : "food", "budget" : 400, "spent" : 450 }
{ "_id" : 2, "category" : "drinks", "budget" : 100, "spent" : 150 }
{ "_id" : 5, "category" : "travel", "budget" : 200, "spent" : 650 }
Using $expr With Conditional Statements:
Some queries require the ability to execute conditional logic when
defining a query filter.
The aggregation framework provides the $cond operator to
express conditional statements.
By using $expr with the $cond operator, you can specify a
conditional filter for your query statement.
Create a sample supplies collection with the following documents:
db.supplies.insertMany([
{ "_id" : 1, "item" : "binder", "qty" : NumberInt("100"), "price" :
NumberDecimal("12") },
{ "_id" : 2, "item" : "notebook", "qty" : NumberInt("200"), "price" :
NumberDecimal("8") },
{ "_id" : 3, "item" : "pencil", "qty" : NumberInt("50"), "price" :
NumberDecimal("6") },
{ "_id" : 4, "item" : "eraser", "qty" : NumberInt("150"), "price" :
NumberDecimal("3") },
{ "_id" : 5, "item" : "legal pad", "qty" : NumberInt("42"), "price" :
NumberDecimal("10") }
])
Assume that for an upcoming sale next month, you want to discount
the prices such that:
If qty is greater than or equal to 100, the discounted price will be
0.5 of the price.
If qty is less than 100, the discounted price is 0.75 of the price.
Before applying the discounts, you would like to know which items in
the supplies collection have a discounted price of less than 5.
The following example uses $expr with $cond to calculate the
discounted price based on the qty and $lt to return documents
whose calculated discount price is less than NumberDecimal("5"):
// Aggregation expression to calculate discounted price
let discountedPrice = {
$cond: {
if: { $gte: ["$qty", 100] },
then: { $multiply: ["$price", NumberDecimal("0.50")] },
else: { $multiply: ["$price", NumberDecimal("0.75")] }
}
};
// Query the supplies collection using the aggregation expression
$jsonSchema:
The $jsonSchema operator matches documents that satisfy the
specified JSON Schema.
The $jsonSchema operator expression has the following syntax:
{ $jsonSchema: <JSON Schema object> }
For example:
{
$jsonSchema: {
required: [ "name", "major", "gpa", "address" ],
properties: {
name: {
bsonType: "string",
description: "must be a string and is required"
},
address: {
bsonType: "object",
required: [ "zipcode" ],
properties: {
"street": { bsonType: "string" },
"zipcode": { bsonType: "string" }
}
}}}}
Behavior
Feature Compatibility
The featureCompatibilityVersion must be set to "3.6" or higher in
order to use $jsonSchema.
Document Validator
You can use $jsonSchema in a document validator to enforce the
specified schema on insert and update operations:
db.createCollection( <collection>, { validator: { $jsonSchema:
<schema> } } )
db.runCommand( { collMod: <collection>, validator:{
$jsonSchema: <schema> } } )
Query Conditions:
You can use $jsonSchema in query conditions for read and write
operations to find documents in the collection that satisfy the
specified schema:
db.collection.find( { $jsonSchema: <schema> } )
db.collection.aggregate( [ { $match: { $jsonSchema: <schema> }
}])
db.collection.updateMany( { $jsonSchema: <schema> },
<update> )
db.collection.deleteOne( { $jsonSchema: <schema> } )
To find documents in the collection that do not satisfy the
specified schema, use the $jsonSchema expression in a $nor
expression. For example:
db.collection.find( { $nor: [ { $jsonSchema: <schema> } ] } )
db.collection.aggregate( [ { $match: { $nor: [ { $jsonSchema:
<schema> } ] } }, ... ] )
db.collection.updateMany( { $nor: [ { $jsonSchema: <schema> } ]
}, <update> )
db.collection.deleteOne( { $nor: [ { $jsonSchema: <schema> } ] }
)
Examples:
Schema Validation
The following db.createCollection() method creates a collection
named students and uses the $jsonSchema operator to set
schema validation rules:
db.createCollection("students", {
validator: {
$jsonSchema: {
bsonType: "object",
required: [ "name", "year", "major", "address" ],
properties: {
name: {
bsonType: "string",
description: "must be a string and is required"
},
year: {
bsonType: "int",
minimum: 2017,
maximum: 3017,
description: "must be an integer in [ 2017, 3017 ] and is
required"
},
major: {
enum: [ "Math", "English", "Computer Science", "History", null
],
description: "can only be one of the enum values and is required"
},
gpa: {
bsonType: [ "double" ],
description: "must be a double if the field exists"
},
address: {
bsonType: "object",
required: [ "city" ],
properties: {
street: {
bsonType: "string",
description: "must be a string if the field exists"
},
city: {
bsonType: "string",
"description": "must be a string and is required"
}
}
}
} } }}]
Given the created validator for the collection, the following insert
operation will fail because gpa is an integer when the validator
requires a double
db.students.insert({
name: "Alice",
year: NumberInt(2019),
major: "History",
gpa: NumberInt(3),
address: {
city: "NYC",
street: "33rd Street"
}
}).
The operation returns the following error:
WriteResult({ "nInserted" : 0, "writeError" : { "code" : 121, "errmsg" :
"Document failed validation" } })
After changing the gpa to a double, the insert succeeds:
db.students.insert({
name: "Alice",
year: NumberInt(2019),
major: "History",
gpa: 3.0,
address: {
city: "NYC",
street: "33rd Street"
}
})
The operation returns the following:
WriteResult({ "nInserted" : 1 })
Query Conditions
You can use $jsonSchema in query conditions for read and write
operations to find documents in the collection that satisfy the
specified schema.
For example, create a sample collection inventory with the following
documents:
db.inventory.insertMany([
{ item: "journal", qty: NumberInt(25), size: { h: 14, w: 21, uom: "cm" },
instock: true },
{ item: "notebook", qty: NumberInt(50), size: { h: 8.5, w: 11, uom: "in"
}, instock: true },
{ item: "paper", qty: NumberInt(100), size: { h: 8.5, w: 11, uom: "in" },
instock: 1 },
{ item: "planner", qty: NumberInt(75), size: { h: 22.85, w: 30, uom:
"cm" }, instock: 1 },
{ item: "postcard", qty: NumberInt(45), size: { h: 10, w: 15.25, uom:
"cm" }, instock: true },
{ item: "apple", qty: NumberInt(45), status: "A", instock: true },
{ item: "pears", qty: NumberInt(50), status: "A", instock: true }
Next, define the following sample schema object:
let myschema = {
required: [ "item", "qty", "instock" ],
properties: {
item: { bsonType: "string" },
qty: { bsonType: "int" },
size: {
bsonType: "object",
required: [ "uom" ],
properties: {
uom: { bsonType: "string" },
h: { bsonType: "double" },
w: { bsonType: "double" }
}
},
instock: { bsonType: "bool" } }}
You can use $jsonSchema to find all documents in the
collection that satisfy the schema:
db.inventory.find( { $jsonSchema: myschema } )
db.inventory.aggregate( [ { $match: { $jsonSchema: myschema } }
])
You can use $jsonSchema with the $nor to find all documents
that do not satisfy the schema:
db.inventory.find( { $nor: [ { $jsonSchema: myschema } ] } )
Or, you can update all documents that do not satisfy the
schema:
db.inventory.updateMany( { $nor: [ { $jsonSchema: myschema } ]
}, { $set: { isValid: false } } )
Or, you can delete all documents that do not satisfy the
schema:
db.inventory.deleteMany( { $nor: [ { $jsonSchema: myschema } ] }
)
Extensions
MongoDB’s implementation of JSON Schema includes the
addition of the bsonType keyword, which allows you to use all
BSON types in the $jsonSchema operator.
bsonType accepts the same string aliases used for the $type
operator.
Omissions
The following are not supported in MongoDB’s implementation of
JSON Schema:
Hypertext definitions in draft 4 of the JSON Schema spec.
The keywords:
$ref
$schema
default
definitions
format
id
The integer type. You must use the BSON type int or long with
the bsonType keyword.
Hypermedia and linking properties of JSON Schema, including
the use of JSON References and JSON Pointers.
Unknown keywords.
$mod:
Select documents where the value of a field divided by a
divisor has the specified remainder (i.e. perform a modulo
operation to select documents).
To specify a $mod expression, use the following syntax:
{ field: { $mod: [ divisor, remainder ] } }
Examples
Use $mod to Select Documents
Consider a collection inventory with the following documents:
{ "_id" : 1, "item" : "abc123", "qty" : 0 }
{ "_id" : 2, "item" : "xyz123", "qty" : 5 }
{ "_id" : 3, "item" : "ijk123", "qty" : 12 }
Then, the following query selects those documents in the inventory
collection where value of the qty field modulo 4 equals 0:
db.inventory.find( { qty: { $mod: [ 4, 0 ] } } )
Output:
{ "_id" : 1, "item" : "abc123", "qty" : 0 }
{ "_id" : 3, "item" : "ijk123", "qty" : 12 }
Not Enough Elements Error
The $mod operator errors when passed an array with fewer than
two elements.
Array with Single Element:
The following operation incorrectly passes the $mod operator an
array that contains a single element:
db.inventory.find( { qty: { $mod: [ 4 ] } } )
The statement results in the following error:
error: {
"$err" : "bad query: BadValue malformed mod, not
enough elements",
"code" : 16810
}
Changed in version 2.6: In previous versions, if passed an
array with one element, the $mod operator uses the
specified element as the divisor and 0 as the remainder
value.
Empty Array:
The following operation incorrectly passes the $mod
operator an empty array:
db.inventory.find( { qty: { $mod: [ ] } } )
The statement results in the following error:
error: {
"$err" : "bad query: BadValue malformed mod, not enough
elements",
"code" : 16810 }
Changed in version 2.6: Previous versions returned the following
error:
error: { "$err" : "mod can't be 0", "code" : 10073 }
Too Many Elements Error:
The $mod operator errors when passed an array with more than
two elements.For example, the following operation attempts to use
the $mod operator with an array that contains four elements:
error: {
"$err" : "bad query: BadValue malformed mod, too many
elements",
"code" : 16810 }
Changed in version 2.6: In previous versions, if passed an array with
more than two elements, the $mod ignores all but the first two
elements.
$regex:
$regex
Provides regular expression capabilities for pattern matching
strings in queries.
MongoDB uses Perl compatible regular expressions (i.e. “PCRE” )
version 8.41 with UTF-8 support.
{ <field>: { $regex: /pattern/, $options: '<options>' } }
{ <field>: { $regex: 'pattern', $options: '<options>' } }
{ <field>: { $regex: /pattern/<options> } }
In MongoDB, you can also use regular expression objects (i.e.
/pattern/) to specify regular expressions:
{ <field>: /pattern/<options> }
Behavior
$regex vs. /pattern/ Syntax
$in Expressions
To include a regular expression in an $in query expression, you can
only use JavaScript regular expression objects (i.e. /pattern/ ). For
example:
{ name: { $in: [ /^acme/i, /^ack/ ] } }
You cannot use $regex operator expressions inside an $in
Implicit AND Conditions for the Field
To include a regular expression in a comma-separated list of
query conditions for the field, use the $regex operator. For
example:.
{ name: { $regex: /acme.*corp/i, $nin: [ 'acmeblahcorp' ] } }
{ name: { $regex: /acme.*corp/, $options: 'i', $nin: [
'acmeblahcorp' ] } }
{ name: { $regex: 'acme.*corp', $options: 'i', $nin: [
'acmeblahcorp' ] } }
x and s Options
To use either the x option or s options, you must use the $regex
operator expression with the $options operator. For example, to
specify the i and the s options, you must use $options for both:
{ name: { $regex: /acme.*corp/, $options: "si" } }
{ name: { $regex: 'acme.*corp', $options: "si" } }
$regex and $not
Starting in 4.0.7, $not operator can perform logical NOT operation on
both:
regular expression objects (i.e. /pattern/)
For example:
db.inventory.find( { item: { $not: /^p.*/ } } )
$regex operator expressions (starting in MongoDB 4.0.7).
For example:
db.inventory.find( { item: { $not: { $regex: "^p.*" } } } )
db.inventory.find( { item: { $not: { $regex: /^p.*/ } } } )
In 4.0.6 and earlier, you could use $not operator with regular
expression objects (i.e. /pattern/) but not with $regex operator
expressions.
Index Use:
A regular expression is a “prefix expression” if it starts with a
caret (^) or a left anchor (\A), followed by a string of simple
symbols.
For example, the regex /^abc.*/ will be optimized by
matching only against the values from the index that start with
abc.
Additionally, while /^a/, /^a.*/, and /^a.*$/ match equivalent
strings, they have different performance characteristics.
All of these expressions use an index if an appropriate index
exists; however, /^a.*/, and /^a.*$/ are slower. /^a/ can stop
scanning after matching the prefix.
Case insensitive regular expression queries generally cannot
use indexes effectively.
The $regex implementation is not collation-aware and is
unable to utilize case-insensitive indexes.
Examples
The following examples use a collection products with the
following documents:
{ "_id" : 100, "sku" : "abc123", "description" : "Single line
description." }
{ "_id" : 101, "sku" : "abc789", "description" : "First line\nSecond
line" }
{ "_id" : 102, "sku" : "xyz456", "description" : "Many spaces before
line" }
{ "_id" : 103, "sku" : "xyz789", "description" : "Multiple\nline
description" }
Perform a LIKE Match:
The following example matches all documents where the sku field
is like "%789":
db.products.find( { sku: { $regex: /789$/ } } )
The example is analogous to the following SQL LIKE statement:
SELECT * FROM products
WHERE sku like "%789";
Perform Case-Insensitive Regular Expression Match:
The following example uses the i option perform a case-insensitive
match for documents with sku value that starts with ABC.
db.products.find( { sku: { $regex: /^ABC/i } } )
The query matches the following documents:
{ "_id" : 100, "sku" : "abc123", "description" : "Single line
description." }
{ "_id" : 101, "sku" : "abc789", "description" : "First line\nSecond line"
}
Multiline Match for Lines Starting with Specified Pattern:
The following example uses the m option to match lines starting
with the letter S for multiline strings:
db.products.find( { description: { $regex: /^S/, $options: 'm' } } )
The query matches the following documents:
{ "_id" : 100, "sku" : "abc123", "description" : "Single line
description." }
{ "_id" : 101, "sku" : "abc789", "description" : "First line\nSecond line"
}
Without the m option, the query would match just the following
document:
{ "_id" : 100, "sku" : "abc123", "description" : "Single line description."
}
If the $regex pattern does not contain an anchor, the pattern
matches against the string as a whole, as in the following example:
db.products.find( { description: { $regex: /S/ } } )
Then, the $regex would match both documents:
{ "_id" : 100, "sku" : "abc123", "description" : "Single line description."
}
{ "_id" : 101, "sku" : "abc789", "description" : "First line\nSecond line"
}
Use the . Dot Character to Match New Line
The following example uses the s option to allow the dot character
(i.e. .) to match all characters including new line as well as the i
option to perform a case-insensitive match:
db.products.find( { description: { $regex: /m.*line/, $options: 'si' } } )
The query matches the following documents:
{ "_id" : 102, "sku" : "xyz456", "description" : "Many spaces before line" }
{ "_id" : 103, "sku" : "xyz789", "description" : "Multiple\nline description" }
Without the s option, the query would have matched only the following
document:
{ "_id" : 102, "sku" : "xyz456", "description" : "Many spaces before line" }
Ignore White Spaces in Pattern:
The following example uses the x option ignore white spaces and the
comments, denoted by the # and ending with the \n in the matching
pattern:
var pattern = "abc #category code\n123 #item number"
db.products.find( { sku: { $regex: pattern, $options: "x" } } )
The query matches the following document:
{ "_id" : 100, "sku" : "abc123", "description" : "Single line description." }
$where:
Use the $where operator to pass either a string containing
a JavaScript expression or a full JavaScript function to the
query system.
The $where provides greater flexibility, but requires that
the database processes the JavaScript expression or
function for each document in the collection.
elemMatch:
Only apply the $where query operator to top-level documents. The
$where query operator will not work inside a nested document, for
instance, in an $elemMatch query.
Considerations:
Do not use global variables.
$where evaluates JavaScript and cannot take advantage of
indexes.
Therefore, query performance improves when you express your
query using the standard MongoDB operators (e.g., $gt, $in).
In general, you should use $where only when you can’t express
your query using another operator.
If you must use $where, try to include at least one other
standard query operator to filter the result set.
Using $where alone requires a collection scan.
Using normal non-$where query statements provides the following
performance advantages:
MongoDB will evaluate non-$where components of query
before $where statements.
If the non-$where statements match no documents, MongoDB
will not perform any query evaluation using $where.
The non-$where query statements may use an index.
Example:
Consider the following documents in the players collection:
{
_id: 12378,
name: "Steve",
username: "steveisawesome",
first_login: "2017-01-01"
}
{
_id: 2,
name: "Anya",
username: "anya",
first_login: "2001-02-02"
}
The following example uses $where and the hex_md5()
JavaScript function to compare the value of the name field to
an MD5 hash and returns any matching document.
db.players.find( { $where: function() {
return (hex_md5(this.name) ==
"9b53e667f30cd329dca1ec9e6a83e994")
} } );
The operation returns the following result:
{
"_id" : 2,
"name" : "Anya",
"username" : "anya",
"first_login" : "2001-02-02"
}
$all:
The $all operator selects the documents where the value of a field is
an array that contains all the specified elements.
To specify an $all expression, use the following prototype:
{ <field>: { $all: [ <value1> , <value2> ... ] } }
Behavior:
Equivalent to $and Operation:
The $all is equivalent to an $and operation of the specified values;
i.e. the following statement:
{ tags: { $all: [ "ssl" , "security" ] } }
is equivalent to:
{ $and: [ { tags: "ssl" }, { tags: "security" } ] }
Nested Array:
When passed an array of a nested array (e.g. [ [ "A" ] ] ), $all can
now match documents where the field contains the nested array
as an element (e.g. field: [ [ "A" ], ... ]), or the field equals the nested
array (e.g. field: [ "A" ]).
For example, consider the following query [1]:
db.articles.find( { tags: { $all: [ [ "ssl", "security" ] ] } } )
The query is equivalent to:
db.articles.find( { $and: [ { tags: [ "ssl", "security" ] } ] } )
which is equivalent to:
db.articles.find( { tags: [ "ssl", "security" ] } )
As such, the $all expression can match documents where the tags
field is an array that contains the nested array [ "ssl", "security" ] or is
an array that equals the nested array:
tags: [ [ "ssl", "security" ], ... ]
tags: [ "ssl", "security" ]
Examples:
The following examples use the inventory collection that contains
the documents:
{
_id: ObjectId("5234cc89687ea597eabee675"),
code: "xyz",
tags: [ "school", "book", "bag", "headphone", "appliance" ],
qty: [
{ size: "S", num: 10, color: "blue" },
{ size: "M", num: 45, color: "blue" },
{ size: "L", num: 100, color: "green" }
]
}
{_id: ObjectId("5234cc8a687ea597eabee676"),
code: "abc",
tags: [ "appliance", "school", "book" ],
qty: [
{ size: "6", num: 100, color: "green" },
{ size: "6", num: 50, color: "blue" },
{ size: "8", num: 100, color: "brown" }
]
}{ _id: ObjectId("5234ccb7687ea597eabee677"), code: "efg",
tags: [ "school", "book" ],
qty: [
{ size: "S", num: 10, color: "blue" },
{ size: "M", num: 100, color: "blue" },
{ size: "L", num: 100, color: "green" }
Use $all to Match Values:
The following operation uses the $all operator to query the
inventory collection for documents where the value of the tags
field is an array whose elements include appliance, school, and
book:
db.inventory.find( { tags: { $all: [ "appliance", "school", "book" ] } } )
The above query returns the following documents:
{
_id: ObjectId("5234cc89687ea597eabee675"),
code: "xyz",
tags: [ "school", "book", "bag", "headphone", "appliance" ],
qty: [
{ size: "S", num: 10, color: "blue" },
{ size: "M", num: 45, color: "blue" },
{ size: "L", num: 100, color: "green" }
]
}{
_id: ObjectId("5234cc8a687ea597eabee676"),
code: "abc",
tags: [ "appliance", "school", "book" ],
qty: [
{ size: "6", num: 100, color: "green" },
{ size: "6", num: 50, color: "blue" },
{ size: "8", num: 100, color: "brown" }
]
}
Use $all with $elemMatch
If the field contains an array of documents, you can use the $all
with the $elemMatch operator.
The following operation queries the inventory collection for
documents where the value of the qty field is an array whose
elements match the $elemMatch criteria:
db.inventory.find( {
qty: { $all: [
{ "$elemMatch" : { size: "M", num: { $gt: 50} }
},
{ "$elemMatch" : { num : 100, color: "green"
}}
]}
})
The query returns the following documents:
{
"_id" : ObjectId("5234ccb7687ea597eabee677"),
"code" : "efg",
"tags" : [ "school", "book"],
"qty" : [
{ "size" : "S", "num" : 10, "color" : "blue" },
{ "size" : "M", "num" : 100, "color" : "blue" },
{ "size" : "L", "num" : 100, "color" : "green" } ] }
{
"_id" : ObjectId("52350353b2eff1353b349de9"),
"code" : "ijk",
"tags" : [ "electronics", "school" ],
"qty" : [
{ "size" : "M", "num" : 100, "color" : "green" }
]
}
The $all operator exists to support queries on arrays.
But you may use the $all operator to select against a non-
array field, as in the following example:
db.inventory.find( { "qty.num": { $all: [ 50 ] } } )
However, use the following form to express the same query:
db.inventory.find( { "qty.num" : 50 } )
Both queries will select all documents in the inventory collection
where the value of the num field equals 50.
$elemMatch:
The $elemMatch operator matches documents that contain an
array field with at least one element that matches all the
specified query criteria.
{ <field>: { $elemMatch: { <query1>, <query2>, ... } } }
If you specify only a single <query> condition in the
$elemMatch expression, you do not need to use $elemMatch.
Behavior
You cannot specify a $where expression in an $elemMatch.
You cannot specify a $text query expression in an
$elemMatch.
Examples
Element Match
Given the following documents in the scores collection:
{ _id: 1, results: [ 82, 85, 88 ] }
{ _id: 2, results: [ 75, 88, 89 ] }
The following query matches only those documents where the
results array contains at least one element that is both greater
than or equal to 80 and is less than 85.
db.scores.find(
{ results: { $elemMatch: { $gte: 80, $lt: 85 } } }
)
The query returns the following document since the element 82
is both greater than or equal to 80 and is less than 85
{ "_id" : 1, "results" : [ 82, 85, 88 ] }
Array of Embedded Documents
Given the following documents in the survey collection:d
{ _id: 1, results: [ { product: "abc", score: 10 }, { product: "xyz",
score: 5 } ] }
{ _id: 2, results: [ { product: "abc", score: 8 }, { product: "xyz",
score: 7 } ] }
{ _id: 3, results: [ { product: "abc", score: 7 }, { product: "xyz",
score: 8 } ] }
The following query matches only those documents where the
results array contains at least one element with both product
equal to "xyz" and score greater than or equal to 8.
db.survey.find(
{ results: { $elemMatch: { product: "xyz", score: { $gte: 8 } } } }
)
Specifically, the query matches the following document:
{ "_id" : 3, "results" : [ { "product" : "abc", "score" : 7 }, { "product" :
"xyz", "score" : 8 } ] }
Single Query Condition:
If you specify a single query predicate in the $elemMatch
expression, $elemMatch is not necessary.
For example, consider the following example where $elemMatch
specifies only a single query predicate { product: "xyz" }:
db.survey.find(
{ results: { $elemMatch: { product: "xyz" } } }
)
Since the $elemMatch only specifies a single condition, the
$elemMatch expression is not necessary, and instead you can use
the following query:
db.survey.find(
{ "results.product": "xyz" }
)
$size:
The $size operator matches any array with the number of elements
specified by the argument. For example:
db.collection.find( { field: { $size: 2 } } );
returns all documents in collection where field is an array with 2
elements.
For instance, the above expression will return { field: [ red, green ]
} and { field: [ apple, lime ] } but not { field: fruit } or { field: [ orange,
lemon, grapefruit ] }. To match fields with only one element within
an array use $size with a value of 1, as follows:
db.collection.find( { field: { $size: 1 } } );
$size does not accept ranges of values.
To select documents based on fields with different numbers of
elements, create a counter field that you increment when you
add elements to a field.
Queries cannot use indexes for the $size portion of a query,
although the other portions of a query can use indexes if
applicable.
Update Operators:
The following modifiers are available for use in update operations;
e.g. in db.collection.update() and db.collection.findAndModify()
Specify the operator expression in a document of the form:
{
<operator1>: { <field1>: <value1>, ... },
<operator2>: { <field2>: <value2>, ... },
...
}
Field Update Operators:
Name Description
$currentDate Sets the value of a field to current
date, either as a Date or a
Timestamp.
$inc Increments the value of the field
by the specified amount.
$min Only updates the field if the
specified value is less than the
existing field value.
$max Only updates the field if the
specified value is greater than
the existing field value.
$mul Multiplies the value of the field by
the specified amount.
$rename Renames a field.
$set Sets the value of a field in a
document.
$unset Removes the specified field from
a document.
Array Update Operator:
Name Description
$addToSet Adds elements to an
array only if they do not
already exist in the set.
$pop Removes the first or last
item of an array.
$pull Removes all array
elements that match a
specified query.
$push Adds an item to an array.
$pullAll Removes all matching
values from an array
Bitwise Operator:
Name Description
$bit Performs bitwise AND, OR,
and XOR updates of
integer values.
Modifiers:
Name Description
Array Query
Summary: Operator
Update
Operator
Thank You………
If you have any quries please write to [email protected]".