Query and Projection Operators
Query and Projection Operators
Comparison
Name Description
$gte Matches values that are greater than or equal to a specified value.
$lte Matches values that are less than or equal to a specified value.
$ne Matches all values that are not equal to a specified value.
Logical
Name Description
Joins query clauses with a logical AND returns all documents that
$and
match the conditions of both clauses.
Joins query clauses with a logical NOR returns all documents that fail
$nor
to match both clauses.
Joins query clauses with a logical OR returns all documents that match
$or
the conditions of either clause.
Element
1
Name Description
2
Name Description
Array
Name Description
Comments
Name Description
3
Name Description
Projection Operators¶
Name Description
4
Comparison Query Operators
Name Description
$lte Matches values that are less than or equal to a specified value.
5
Name Description
$ne Matches all values that are not equal to a specified value.
6
$eq
$eq
copy
copied
{ <field>: { $eq: <value> } }
Behavior
Comparison Order
7
The expression { field: <value> } implicitly specifies a match
on <value>. MongoDB translates the implicit match to a more
explicit form.
Security Implications
Always use the explicit form { field: { $eq: <value> } } with user-
supplied input to avoid problems with maliciously formed queries.
Examples
copy
copied
{ _id: 1, item: { name: "ab", code: "123" }, qty: 15,
tags: [ "A", "B", "C" ] }
{ _id: 2, item: { name: "cd", code: "123" }, qty: 20,
tags: [ "B" ] }
{ _id: 3, item: { name: "ij", code: "456" }, qty: 25,
tags: [ "A", "B" ] }
{ _id: 4, item: { name: "xy", code: "456" }, qty: 30,
tags: [ "B", "A" ] }
{ _id: 5, item: { name: "mn", code: "000" }, qty: 20,
tags: [ [ "A", "B" ], "C" ] }
copy
copied
db.inventory.find( { qty: { $eq: 20 } } )
copy
copied
db.inventory.find( { qty: 20 } )
copy
copied
{ _id: 2, item: { name: "cd", code: "123" }, qty: 20,
tags: [ "B" ] }
{ _id: 5, item: { name: "mn", code: "000" }, qty: 20,
tags: [ [ "A", "B" ], "C" ] }
copy
copied
db.inventory.find( { "item.name": { $eq: "ab" } } )
copy
copied
9
db.inventory.find( { "item.name": "ab" } )
copy
copied
{ _id: 1, item: { name: "ab", code: "123" }, qty: 15,
tags: [ "A", "B", "C" ] }
SEE ALSO
Query Embedded Documents
copy
copied
db.inventory.find( { tags: { $eq: "B" } } )
copy
copied
db.inventory.find( { tags: "B" } )
copy
copied
{ _id: 1, item: { name: "ab", code: "123" }, qty: 15,
tags: [ "A", "B", "C" ] }
{ _id: 2, item: { name: "cd", code: "123" }, qty: 20,
tags: [ "B" ] }
{ _id: 3, item: { name: "ij", code: "456" }, qty: 25,
tags: [ "A", "B" ] }
10
{ _id: 4, item: { name: "xy", code: "456" }, qty: 30,
tags: [ "B", "A" ] }
SEE ALSO
$elemMatch, Query Arrays
The query will also match documents where the value of the tags field
[1]
is the string "B".
copy
copied
db.inventory.find( { tags: { $eq: [ "A", "B" ] } } )
copy
copied
db.inventory.find( { tags: [ "A", "B" ] } )
copy
copied
{ _id: 3, item: { name: "ij", code: "456" }, qty: 25,
tags: [ "A", "B" ] }
{ _id: 5, item: { name: "mn", code: "000" }, qty: 20,
tags: [ [ "A", "B" ], "C" ] }
11
Regex Match Behaviour
copy
copied
{ _id: 001, company: "MongoDB" }
{ _id: 002, company: "MongoDB2" }
$eq match on a string
copy
copied
db.collection.find( { company: "MongoDB" }, {_id: 0
})
db.collection.find( { company: { $eq: "MongoDB" } }
, {_id: 0 } )
{ "company" : "MongoDB" }
$eq match on a regular expression
copy
copied
db.collection.find( { company: { $eq: /MongoDB/ } }
, {_id: 0 } )
12
Regular expression matches
copy
copied
db.collection.find( { company: /MongoDB/ }, {_id: 0
})
db.collection.find( { company: { $regex: /MongoDB/
} }, {_id: 0 } )
{ "company" : "MongoDB" }
{ "company" : "MongoDB2" }
13
$gt
$gt
copy
copied
Consider the following example that uses the $gt operator with
a field from an embedded document:
copy
copied
14
This update() operation will set the value of the price field in
the first document found containing the embedded
document carrier whose fee field value is greater than 2.
copy
copied
db.inventory.update(
{ "carrier.fee": { $gt: 2 } },
{ $set: { price: 9.99 } },
{ multi: true }
)
15
$gte
$gte
copy
copied
copy
copied
16
This update() operation will set the value of the price field
that contain the embedded document carrier whose fee field
value is greater than or equal to 2.
SEE ALSO
find(), update(), $set.
17
$in
On this page
Examples
Use the $in Operator to Match Values
Use the $in Operator to Match Values in an Array
Use the $in Operator with a Regular Expression
$in
copy
copied
{ field: { $in: [<value1>, <value2>, ... <valueN> ]
} }
If the field holds an array, then the $in operator selects the
documents whose field holds an array that contains at least
one element that matches a value in the specified array (for
example, <value1>, <value2>, and so on).
NOTE
This document describes the $in query operator. For
the $in aggregation operator, see $in (aggregation).
Examples
18
Consider the following example:
copy
copied
db.inventory.find( { qty: { $in: [ 5, 15 ] } } )
copy
copied
{ _id: 1, item: "abc", qty: 10, tags: [ "school", "cl
othing" ], sale: false }
Then, the following update() operation will set the sale field
value to true where the tags field holds an array with at least one
element matching either "appliances" or "school".
copy
copied
db.inventory.update(
{ tags: { $in: ["appliances", "s
chool"] } },
{ $set: { sale:true } }
)
Query an Array
19
Query an Array of Embedded Documents
Query Documents
copy
copied
db.inventory.find( { tags: { $in: [ /^be/, /^st/ ] }
} )
SEE ALSO
find(), update(), $or, $set, $elemMatch.
20
$lt
$lt
$lt selects the documents where the value of the field is less
than (i.e. <) the specified value.
copy
copied
copy
copied
21
This update() operation will set the price field value in the
documents that contain the embedded
document carrier whose fee field value is less than 20.
SEE ALSO
find(), update(), $set.
-==============================================
22
$lte
$lte
$lte selects the documents where the value of the field is less
than or equal to (i.e. <=) the specified value.
copy
copied
copy
copied
23
This update() operation will set the price field value in the
documents that contain the embedded
document carrier whose fee field value is less than or equal
to 5.
24
$ne
$ne
$ne selects the documents where the value of the field is not
equal to the specified value. This includes documents that do
not contain the field.
copy
copied
copy
copied
25
This update() operation will set the qty field value in the
documents that contain the embedded
document carrier whose state field value does not equal
“NY”, or where the state field or the carrier embedded
document do not exist.
26
$nin
$nin
copy
copied
db.inventory.find( { qty: { $nin: [ 5, 15 ] } } )
If the field holds an array, then the $nin operator selects the
documents whose field holds an array with no element equal
to a value in the specified array (e.g. <value1>, <value2>, etc.).
27
Consider the following query:
copy
copied
db.inventory.update( { tags: { $nin: [ "appliances"
, "school" ] } }, { $set: { sale: false } } )
SEE ALSO
find(), update(), $set.
28
Logical Query Operators
NOTE
For details on specific operator, including syntax and examples, click
on the specific operator to go to its reference page.
Name Description
29
$and
On this page
Examples
$and
NOTE
MongoDB provides an implicit AND operation when specifying a comma
separated list of expressions.
Examples
copy
copied
db.inventory.find( { $and: [ { price: { $ne: 1.99 } }
, { price: { $exists: true } } ] } )
This query will select all documents in the inventory collection where:
30
the price field value is not equal to 1.99 and
the price field exists.
copy
copied
db.inventory.find( { price: { $ne: 1.99, $exists: tru
e } } )
copy
copied
db.inventory.find( {
$and: [
{ $or: [ { qty: { $lt : 10 } }, { qty : { $gt
: 50 } } ] },
{ $or: [ { sale: true }, { price : { $lt : 5
} } ] }
]
} )
the qty field value is less than 10 or greater than 50, and
the sale field value is equal to true or the price field value
is less than 5.
31
$not
On this page
Behavior
$not
copy
copied
db.inventory.find( { price: { $not: { $gt: 1.99 } }
} )
Remember that the $not operator only affects other operators and
cannot check fields and documents independently. So, use
32
the $not operator for logical disjunctions and the $ne operator to test
the contents of fields directly.
Behavior
copy
copied
copy
copied
copy
copied
import re
for noMatch in db.inventory.find( { "item": { "$
not": re.compile("^p.*") } } ):
print noMatch
34
$nor
On this page
Examples
$nor
copy
copied
{ $nor: [ { <expression1> }, { <expression2> }, ...
{ <expressionN> } ] }
SEE ALSO
find(), update(), $or, $set, and $exists.
Examples
Consider the following query which uses only the $nor operator:
copy
copied
db.inventory.find( { $nor: [ { price: 1.99 }, { sale:
true } ] } )
35
contain the price field whose value is not equal to 1.99 and
contain the sale field whose value is not equal to true or
contain the price field whose value is not equal
to 1.99 but do not contain the sale field or
do not contain the price field but contain the sale field
whose value is not equal to true or
do not contain the price field and do not contain
the sale field
copy
copied
db.inventory.find( { $nor: [ { price: 1.99 }, { qty:
{ $lt: 20 } }, { sale: true } ] } )
copy
36
copied
db.inventory.find( { $nor: [ { price: 1.99 }, { price
: { $exists: false } },
{ sale: true }, { sale:
{ $exists: false } } ] } )
contain the price field whose value is not equal to 1.99 and
contain the sale field whose value is not equal to true
37
$or
On this page
Behaviors
$or
copy
copied
{ $or: [ { <expression1> }, { <expression2> }, ...
, { <expressionN> } ] }
copy
copied
db.inventory.find( { $or: [ { quantity: { $lt: 20 }
}, { price: 10 } ] } )
Behaviors
38
supported by indexes, MongoDB performs index scans. That is,
for MongoDB to use indexes to evaluate an $or expression, all the
clauses in the $or expression must be supported by indexes.
Otherwise, MongoDB will perform a collection scan.
When using indexes with $or queries, each clause of an $or can
use its own index. Consider the following query:
copy
copied
db.inventory.find( { $or: [ { quantity: { $lt: 20 } }
, { price: 10 } ] } )
copy
copied
db.inventory.createIndex( { quantity: 1 } )
db.inventory.createIndex( { price: 1 } )
If $or includes a $text query, all clauses in the $or array must be
supported by an index. This is because a $text query must use
an index, and $or can only use indexes if all its clauses are
supported by indexes. If the $text query cannot use an index, the
query will return an error.
39
includes $nearSphere and $near). $or cannot contain a near
clause with any other clause.
When using $or with <expressions> that are equality checks for
the value of the same field, use the $in operator instead of
the $or operator.
copy
copied
db.inventory.find ( { quantity: { $in: [20, 50] } } )
40
Element Query Operators
NOTE
For details on specific operator, including syntax and examples, click
on the specific operator to go to its reference page.
Name Description
41
$exists
On this page
Definition
Examples
Definition
$exists
SEE ALSO
$nin, $in, and Query for Null or Missing Fields.
Examples
42
Consider the following example:
copy
copied
This query will select all documents in the inventory collection where
the qty field exists and its value does not equal 5 or 15.
Null Values
copy
copied
{ a: 5, b: 5, c: null }
{ a: 3, b: null, c: 8 }
{ a: null, b: 3, c: 9 }
{ a: 1, b: 2, c: 3 }
{ a: 2, c: 5 }
{ a: 3, b: 2 }
{ a: 4 }
{ b: 2, c: 4 }
{ b: 2 }
{ c: 6 }
$exists: true
43
copy
copied
The results consist of those documents that contain the field a, including
the document whose field a contains a null value:
copy
copied
{ a: 5, b: 5, c: null }
{ a: 3, b: null, c: 8 }
{ a: null, b: 3, c: 9 }
{ a: 1, b: 2, c: 3 }
{ a: 2, c: 5 }
{ a: 3, b: 2 }
{ a: 4 }
$exists: false
copy
copied
copy
copied
44
{ a: 2, c: 5 }
{ a: 4 }
{ c: 6 }
45
$type
On this page
Definition
Behavior
Examples
Querying by Array Type
Additional Information
Definition
$type
copy
copied
{ field: { $type: <BSON type> } }
You can specify either the number or alias for the BSON type
copy
copied
46
{ field: { $type: [ <BSON type1> , <BSON type2>, ..
. ] } }
The above query will match documents where the field value is
any of the listed types. The types specified in the array can be
either numeric or string aliases.
SEE ALSO
Behavior
Arrays
47
element of type array. For example, given the following
documents:
copy
copied
{ "data" : [ "values", [ "values" ] ] }
{ "data" : [ "values" ] }
Available Types
Double 1 “double”
String 2 “string”
Object 3 “object”
48
Type Number Alias Notes
Array 4 “array”
ObjectId 7 “objectId”
Boolean 8 “bool”
Date 9 “date”
Null 10 “null”
11 “regex”
Regular
49
Type Number Alias Notes
Expression
JavaScript 13 “javascript”
Timestamp 17 “timestamp”
50
Type Number Alias Notes
$type supports the number alias, which will match against the
following BSON types:
double
32-bit integer
64-bit integer
decimal
SEE ALSO
$isNumber New in MongoDB 4.4
51
MinKey and MaxKey are used in comparison operations and exist
primarily for internal use. For all possible BSON element
values, MinKey will always be the smallest value while MaxKey will
always be the greatest value.
Querying for minKey or maxKey with $type will only return fields
that match the special MinKey or MaxKey values.
copy
copied
{ "_id" : 1, x : { "$minKey" : 1 } }
{ "_id" : 2, y : { "$maxKey" : 1 } }
copy
copied
db.data.find( { x: { $type: "minKey" } } )
copy
copied
db.data.find( { y: { $type: "maxKey" } } )
Examples
copy
copied
52
db.addressBook.insertMany(
[
{ "_id" : 1, address : "2030 Martian Way", zipC
ode : "90698345" },
{ "_id" : 2, address: "156 Lunar Place", zipCod
e : 43339374 },
{ "_id" : 3, address : "2324 Pluto Place", zipC
ode: NumberLong(3921412) },
{ "_id" : 4, address : "55 Saturn Ring" , zipCo
de : NumberInt(88602117) },
{ "_id" : 5, address : "104 Venus Drive", zipCo
de : ["834847278", "1893289032"]}
]
)
copy
copied
db.addressBook.find( { "zipCode" : { $type : 2 } } );
db.addressBook.find( { "zipCode" : { $type : "string"
} } );
copy
copied
{ "_id" : 1, "address" : "2030 Martian Way", "zipCode
" : "90698345" }
{ "_id" : 5, "address" : "104 Venus Drive", "zipCode"
: [ "834847278", "1893289032" ] }
53
The following queries return all documents where zipCode is
the BSON type double or is an array containing an element of the
specified type:
copy
copied
db.addressBook.find( { "zipCode" : { $type : 1 } } )
db.addressBook.find( { "zipCode" : { $type : "double"
} } )
copy
copied
{ "_id" : 2, "address" : "156 Lunar Place", "zipCode"
: 43339374 }
copy
copied
db.addressBook.find( { "zipCode" : { $type : "number"
} } )
copy
copied
{ "_id" : 2, "address" : "156 Lunar Place", "zipCode"
: 43339374 }
{ "_id" : 3, "address" : "2324 Pluto Place", "zipCode
" : NumberLong(3921412) }
{ "_id" : 4, "address" : "55 Saturn Ring", "zipCode"
: 88602117 }
54
Querying by Multiple Data Type
copy
copied
db.grades.insertMany(
[
{ "_id" : 1, name : "Alice King" , classAverage
: 87.333333333333333 },
{ "_id" : 2, name : "Bob Jenkins", classAverage
: "83.52" },
{ "_id" : 3, name : "Cathy Hart", classAverage:
"94.06" },
{ "_id" : 4, name : "Drew Williams" , classAver
age : NumberInt("93") }
]
)
copy
copied
db.grades.find( { "classAverage" : { $type : [ 2 , 1
] } } );
db.grades.find( { "classAverage" : { $type : [ "strin
g" , "double" ] } } );
copy
copied
55
{ "_id" : 1, "name" : "Alice King", "classAverage" :
87.33333333333333 }
{ "_id" : 2, "name" : "Bob Jenkins", "classAverage" :
"83.52" }
{ "_id" : 3, "name" : "Cathy Hart", "classAverage" :
"94.06" }
copy
copied
{
"_id": 1,
"address": {
"building": "230",
"coord": [ -73.996089, 40.675018 ],
"street": "Huntington St",
"zipcode": "11231"
},
"borough": "Brooklyn",
"cuisine": "Bakery",
"grades": [
{ "date": new Date(1393804800000), "grade": "C"
, "score": 15 },
{ "date": new Date(1378857600000), "grade": "C"
, "score": 16 },
{ "date": new Date(1358985600000), "grade": Min
Key(), "score": 30 },
{ "date": new Date(1322006400000), "grade": "C"
, "score": 15 }
],
"name": "Dirty Dan's Donuts",
"restaurant_id": "30075445"
56
}
And maxKey for any grade that is the highest passing grade:
copy
copied
{
"_id": 2,
"address": {
"building": "1166",
"coord": [ -73.955184, 40.738589 ],
"street": "Manhattan Ave",
"zipcode": "11222"
},
"borough": "Brooklyn",
"cuisine": "Bakery",
"grades": [
{ "date": new Date(1393804800000), "grade": Max
Key(), "score": 2 },
{ "date": new Date(1378857600000), "grade": "B"
, "score": 6 },
{ "date": new Date(1358985600000), "grade": Max
Key(), "score": 3 },
{ "date": new Date(1322006400000), "grade": "B"
, "score": 5 }
],
"name": "Dainty Daisey's Donuts",
"restaurant_id": "30075449"
}
copy
copied
57
db.restaurants.find(
{ "grades.grade" : { $type : "minKey" } }
)
This returns
copy
copied
{
"_id" : 1,
"address" : {
"building" : "230",
"coord" : [ -73.996089, 40.675018 ],
"street" : "Huntington St",
"zipcode" : "11231"
},
"borough" : "Brooklyn",
"cuisine" : "Bakery",
"grades" : [
{ "date" : ISODate("2014-03-03T00:00:00Z"), "gr
ade" : "C", "score" : 15 },
{ "date" : ISODate("2013-09-11T00:00:00Z"), "gr
ade" : "C", "score" : 16 },
{ "date" : ISODate("2013-01-24T00:00:00Z"), "gr
ade" : { "$minKey" : 1 }, "score" : 30 },
{ "date" : ISODate("2011-11-23T00:00:00Z"), "gr
ade" : "C", "score" : 15 }
],
"name" : "Dirty Dan's Donuts",
"restaurant_id" : "30075445"
}
58
copy
copied
db.restaurants.find(
{ "grades.grade" : { $type : "maxKey" } }
)
This returns
copy
copied
{
"_id" : 2,
"address" : {
"building" : "1166",
"coord" : [ -73.955184, 40.738589 ],
"street" : "Manhattan Ave",
"zipcode" : "11222"
},
"borough" : "Brooklyn",
"cuisine" : "Bakery",
"grades" : [
{ "date" : ISODate("2014-03-03T00:00:00Z"), "gr
ade" : { "$maxKey" : 1 }, "score" : 2 },
{ "date" : ISODate("2013-09-11T00:00:00Z"), "gr
ade" : "B", "score" : 6 },
{ "date" : ISODate("2013-01-24T00:00:00Z"), "gr
ade" : { "$maxKey" : 1 }, "score" : 3 },
{ "date" : ISODate("2011-11-23T00:00:00Z"), "gr
ade" : "B", "score" : 5 }
],
"name" : "Dainty Daisey's Donuts",
"restaurant_id" : "30075449"
}
59
A collection named SensorReading contains the following
documents:
copy
copied
{
"_id": 1,
"readings": [
25,
23,
[ "Warn: High Temp!", 55 ],
[ "ERROR: SYSTEM SHUTDOWN!", 66 ]
]
},
{
"_id": 2,
"readings": [
25,
25,
24,
23
]
},
{
"_id": 3,
"readings": [
22,
24,
[]
]
},
{
"_id": 4,
"readings": []
},
{
60
"_id": 5,
"readings": 24
}
copy
copied
db.SensorReading.find( { "readings" : { $type: "array
" } } )
copy
copied
{
"_id": 1,
"readings": [
25,
23,
[ "Warn: High Temp!", 55 ],
[ "ERROR: SYSTEM SHUTDOWN!", 66 ]
]
},
{
"_id": 2,
"readings": [
25,
25,
24,
23
]
},
{
"_id": 3,
61
"readings": [
22,
24,
[]
]
},
{
"_id": 4,
"readings": []
}
Additional Information
62
Evaluation Query Operators
NOTE
For details on specific operator, including syntax and examples, click
on the specific operator to go to its reference page.
Name Description
63
Name Description
64
$expr
On this page
Definition
Behavior
Examples
Definition
$expr
copy
copied
{ $expr: { <expression> } }
Behavior
$expr can build query expressions that compare fields from the
same document in a $match stage.
o 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.
o $expr only uses indexes on the from collection for equality
matches in a $match stage.
65
$expr does not support multikey indexes.
Examples
copy
copied
{ "_id" : 1, "category" : "food", "budget": 400, "spe
nt": 450 }
{ "_id" : 2, "category" : "drinks", "budget": 100, "s
pent": 150 }
{ "_id" : 3, "category" : "clothes", "budget": 100, "
spent": 50 }
{ "_id" : 4, "category" : "misc", "budget": 500, "spe
nt": 300 }
{ "_id" : 5, "category" : "travel", "budget": 200, "s
pent": 650 }
copy
copied
db.monthlyBudget.find( { $expr: { $gt: [ "$spent" , "
$budget" ] } } )
copy
copied
{ "_id" : 1, "category" : "food", "budget" : 400, "sp
ent" : 450 }
66
{ "_id" : 2, "category" : "drinks", "budget" : 100, "
spent" : 150 }
{ "_id" : 5, "category" : "travel", "budget" : 200, "
spent" : 650 }
copy
copied
db.supplies.insertMany([
{ "_id" : 1, "item" : "binder", "qty" : NumberInt(
"100"), "price" : NumberDecimal("12") },
{ "_id" : 2, "item" : "notebook", "qty" : NumberIn
t("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" : NumberI
nt("42"), "price" : NumberDecimal("10") }
])
67
If qty is less than 100, the discounted price is 0.75 of
the price.
copy
copied
// Aggregation expression to calculate discounted pri
ce
let discountedPrice = {
$cond: {
if: { $gte: ["$qty", 100] },
then: { $multiply: ["$price", NumberDecimal("0.
50")] },
else: { $multiply: ["$price", NumberDecimal("0.
75")] }
}
};
The following table shows the discounted price for each document
and whether discounted price is less
than NumberDecimal("5") (i.e. whether the document meets the
query condition).
68
<
Document Discounted Price
NumberDecimal(“5”)
{“_id”: 1, “item”:
“binder”, “qty”: 100,
NumberDecimal(“6.00”) false
“price”:
NumberDecimal(“12”) }
{“_id”: 2, “item”:
“noteboook”, “qty”: 200,
NumberDecimal(“4.00”) true
“price”:
NumberDecimal(“8”) }
{“_id”: 3, “item”:
“pencil”, “qty”: 50,
NumberDecimal(“4.50”) true
“price”:
NumberDecimal(“6”) }
{“_id”: 4, “item”:
“eraser”, “qty”: 150,
NumberDecimal(“1.50”) true
“price”:
NumberDecimal(“3”) }
69
<
Document Discounted Price
NumberDecimal(“5”)
copy
copied
{ "_id" : 2, "item" : "notebook", "qty": 200 , "price
": NumberDecimal("8") }
{ "_id" : 3, "item" : "pencil", "qty": 50 , "price":
NumberDecimal("6") }
{ "_id" : 4, "item" : "eraser", "qty": 150 , "price":
NumberDecimal("3") }
70
$jsonSchema
On this page
Definition
Behavior
Examples
JSON Schema
Definition
$jsonSchema
copy
copied
{ $jsonSchema: <JSON Schema object> }
copy
copied
{ <keyword1>: <value1>, ... }
For example:
copy
copied
71
{
$jsonSchema: {
required: [ "name", "major", "gpa", "address"
],
properties: {
name: {
bsonType: "string",
description: "must be a string and is re
quired"
},
address: {
bsonType: "object",
required: [ "zipcode" ],
properties: {
"street": { bsonType: "string" },
"zipcode": { bsonType: "string" }
}
}
}
}
}
NOTE
MongoDB supports draft 4 of JSON Schema, including core
specification and validation specification, with some differences.
See Extensions and Omissions for details.
For more information about JSON Schema, see the official
website.
Behavior
Feature Compatibility
72
The featureCompatibilityVersion must be set to "3.6" or higher in
order to use $jsonSchema.
Document Validator
copy
copied
db.createCollection( <collection>, { validator: { $js
onSchema: <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:
73
db.collection.updateMany( { $nor: [ { $jsonSchema: <s
chema> } ] }, <update> )
db.collection.deleteOne( { $nor: [ { $jsonSchema: <sc
hema> } ] } )
Examples
Schema Validation
copy
copied
db.createCollection("students", {
validator: {
$jsonSchema: {
bsonType: "object",
required: [ "name", "year", "major", "addres
s" ],
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: {
74
enum: [ "Math", "English", "Computer S
cience", "History", null ],
description: "can only be one of the e
num 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 i
f the field exists"
},
city: {
bsonType: "string",
"description": "must be a string
and is required"
}
}
}
}
}
}
})
copy
75
copied
db.students.insert({
name: "Alice",
year: NumberInt(2019),
major: "History",
gpa: NumberInt(3),
address: {
city: "NYC",
street: "33rd Street"
}
})
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 121,
"errmsg" : "Document failed validation"
}
})
copy
copied
db.students.insert({
name: "Alice",
year: NumberInt(2019),
major: "History",
gpa: 3.0,
address: {
city: "NYC",
street: "33rd Street"
}
})
76
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.
copy
copied
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 }
])
copy
copied
let myschema = {
77
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" }
}
}
copy
copied
db.inventory.find( { $jsonSchema: myschema } )
db.inventory.aggregate( [ { $match: { $jsonSchema: my
schema } } ] )
You can use $jsonSchema with the $nor to find all documents
that do not satisfy the schema:
copy
copied
db.inventory.find( { $nor: [ { $jsonSchema: myschema
} ] } )
Or, you can update all documents that do not satisfy the schema:
78
copy
copied
db.inventory.updateMany( { $nor: [ { $jsonSchema: mys
chema } ] }, { $set: { isValid: false } } )
Or, you can delete all documents that do not satisfy the schema:
copy
copied
db.inventory.deleteMany( { $nor: [ { $jsonSchema: mys
chema } ] } )
JSON Schema
Available Keywords
NOTE
MongoDB implements a subset of keywords available in JSON
Schema. For a complete list of omissions, see Omissions.
79
Keyword Type Definition Behavior
aliases
array of
JSON Field must match all specified
allOf all types
Schema schemas
objects
array of
Field must match at least one
anyOf all types JSON
of the specified schemas
Schema
80
Keyword Type Definition Behavior
objects
array of
JSON Field must match exactly one
oneOf all types
Schema of the specified schemas
objects
a JSON
Field must not match the
not all types Schema
schema
object
If true, minimum is an
number exclusive minimum.
exclusiveMinimum boolean
s Otherwise, it is an inclusive
minimum.
81
Keyword Type Definition Behavior
string
Field must match the regular
pattern strings containin
expression
g a regex
Defaults to true.
82
Keyword Type Definition Behavior
In addition
to properties requirements
patternProperties objects object , each property name of this
object must be a valid regular
expression
83
Keyword Type Definition Behavior
Extensions
Omissions
84
$mod
On this page
Examples
$mod
copy
copied
Examples
copy
copied
85
Then, the following query selects those documents in
the inventory collection where value of the qty field
modulo 4 equals 0:
copy
copied
copy
copied
The $mod operator errors when passed an array with fewer than
two elements.
copy
copied
copy
86
copied
error: {
"$err" : "bad query: BadValue malformed mod, not
enough elements",
"code" : 16810
}
Empty Array
copy
copied
copy
copied
error: {
"$err" : "bad query: BadValue malformed mod, not
enough elements",
"code" : 16810
}
The $mod operator errors when passed an array with more than
two elements.
87
copy
copied
error: {
"$err" : "bad query: BadValue malformed mod, too
many elements",
"code" : 16810
}
88
$regex
On this page
Definition
Behavior
Examples
Definition
$regex
copy
copied
copy
copied
89
{ <field>: /pattern/<options> }
$options
Optio
Description Syntax Restrictions
n
Case insensitivity to
match upper and lower
cases. For an example,
i
see Perform Case-
Insensitive Regular
Expression Match.
90
Optio
Description Syntax Restrictions
n
“Extended” capability
to ignore all white space
characters in
the $regex pattern
unless escaped or
included in a character
class. Requires $regex with $options s
x
yntax
Additionally, it ignores
characters in-between
and including an un-
escaped hash/pound (#)
character and the next
new line, so that you
may include comments
91
Optio
Description Syntax Restrictions
n
in complicated patterns.
This only applies to
data characters; white
space characters may
never appear within
special character
sequences in a pattern.
NOTE
The $regex operator does not support the global search
modifier g.
Behavior
92
$in Expressions
copy
copied
copy
copied
x and s Options
93
copy
copied
PCRE vs JavaScript
copy
copied
copy
copied
94
copy
copied
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
95
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
copy
copied
The following example matches all documents where the sku field
is like "%789":
copy
copied
copy
copied
96
SELECT * FROM products
WHERE sku like "%789";
copy
copied
copy
copied
copy
copied
97
The query matches the following documents:
copy
copied
Without the m option, the query would match just the following
document:
copy
copied
copy
copied
copy
copied
98
{ "_id" : 101, "sku" : "abc789", "description" : "Fir
st line\nSecond 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:
copy
copied
copy
copied
Without the s option, the query would have matched only the
following document:
copy
copied
99
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:
copy
copied
copy
copied
100
$text
On this page
Definition
Behavior
Examples
Definition
$text
copy
copied
{
$text:
{
$search: <string>,
$language: <string>,
$caseSensitive: <boolean>,
$diacriticSensitive: <boolean>
}
101
}
102
Field Type Description
103
Field Type Description
Insensitivity.
Behavior
Restrictions
104
The $match stage that includes a $text must be
the first stage in the pipeline.
A text operator can only occur once in the stage.
The text operator expression cannot appear
in $or or $not expressions.
The text search, by default, does not return the matching
documents in order of matching scores. To sort by
descending score, use the $meta aggregation expression in
the $sort stage.
$search Field
Phrases
copy
copied
"\"ssl certificate\""
copy
copied
105
"\"ssl certificate\" authority key"
Negations
The $text operator adds all negations to the query with the
logical AND operator.
Match Operation
Stop Words
Stemmed Words
106
Case Sensitive Search and Stemmed Words
Case Insensitivity
$caseSensitive Option
107
First searches the text index for case insensitive and
diacritic matches.
Then, to return just the documents that match the case of the
search terms, the $text query operation includes an
additional stage to filter out the documents that do not match
the specified case.
SEE ALSO
Stemmed Words
Diacritic Insensitivity
$diacriticSensitive Option
108
the $text operator has no effect with earlier versions of
the text index.
SEE ALSO
Stemmed Words
Text Score
109
on the processing of the $text operation. See $meta projection
operator for details on accessing the score for projection or sort.
Examples
copy
copied
copy
copied
db.articles.insert(
[
{ _id: 1, subject: "coffee", author: "xyz", view
s: 50 },
{ _id: 2, subject: "Coffee Shopping", author: "e
fg", views: 5 },
{ _id: 3, subject: "Baking a cake", author: "abc
", views: 90 },
{ _id: 4, subject: "baking", author: "xyz", view
s: 100 },
{ _id: 5, subject: "Café Con Leche", author: "ab
c", views: 200 },
{ _id: 6, subject: "Сырники", author: "jkl", vie
ws: 80 },
{ _id: 7, subject: "coffee and cream", author: "
efg", views: 10 },
110
{ _id: 8, subject: "Cafe con Leche", author: "xy
z", views: 10 }
]
)
copy
copied
This query returns the documents that contain the term coffee in
the indexed subject field, or more precisely, the stemmed version
of the word:
copy
copied
111
The following query specifies a $search string of three terms
delimited by space, "bake coffee cake":
copy
copied
copy
copied
copy
112
copied
copy
copied
copy
copied
copy
copied
113
{ "_id" : 7, "subject" : "coffee and cream", "author"
: "efg", "views" : 10 }
{ "_id" : 1, "subject" : "coffee", "author" : "xyz",
"views" : 50 }
SEE ALSO
Negations, Stemmed Words
The following query specifies es, i.e. Spanish, as the language that
determines the tokenization, stemming, and stop words:
copy
copied
db.articles.find(
{ $text: { $search: "leche", $language: "es" } }
)
copy
copied
114
The $text expression can also accept the language by
name, spanish. See Text Search Languages for the supported
languages.
SEE ALSO
Case Insensitivity
copy
copied
Using the version 3 text index, the query matches the following
documents.
copy
copied
115
{ "_id" : 8, "subject" : "Cafe con Leche", "author" :
"xyz", "views" : 10 }
With the previous versions of the text index, the query would not
match any document.
SEE ALSO
Case Insensitivity, Diacritic Insensitivity, Stemmed Words, Text
Indexes
copy
copied
copy
copied
116
Case Insensitivity, Case Sensitive Search and Stemmed Words
copy
copied
db.articles.find( {
$text: { $search: "\"Café Con Leche\"", $caseSensi
tive: true }
} )
copy
copied
117
copy
copied
copy
copied
copy
copied
118
The query only matches the following document:
copy
copied
copy
copied
db.articles.find(
{ $text: { $search: "leches -cafés", $diacriticSens
itive: true } }
)
copy
copied
119
{ "_id" : 8, "subject" : "Cafe con Leche", "author" :
"xyz" }
SEE ALSO
Diacritic Sensitive Search and Stemmed Words, Diacritic
Insensitivity, Case Insensitivity
The following query performs a text search for the term cake and
uses the $meta operator in the projection document to append the
relevance score to each matching document:
copy
copied
db.articles.find(
{ $text: { $search: "cake" } },
{ score: { $meta: "textScore" } }
)
copy
120
copied
db.articles.find(
{ $text: { $search: "cake" } }
).sort( { score: { $meta: "textScore" } } )
As a result, you can sort the resulting documents by their search
relevance without projecting the textScore.
copy
copied
db.articles.find(
{ $text: { $search: "cake" } } ,
{ score: { $meta: "textScore" } }
).sort( { ignoredName: { $meta: "textScore" } } )
In previous versions of MongoDB, if { $meta: "textScore" } is
included in both the projection and sort, you must specify the same
field name for the expression.
In MongoDB 4.2 and earlier, to sort by the text score, include
the same $meta expression in both the projection document and the
sort expression. The following query searches for the
term coffee and sorts the results by the descending score:
copy
121
copied
db.articles.find(
{ $text: { $search: "coffee" } },
{ score: { $meta: "textScore" } }
).sort( { score: { $meta: "textScore" } } )
The query returns the matching documents sorted by descending
score.
SEE ALSO
$meta
The following query searches for the term coffee and sorts the
results by the descending score, limiting the results to the top two
matching documents:
copy
copied
db.articles.find(
{ $text: { $search: "coffee" } },
{ score: { $meta: "textScore" } }
).sort( { score: { $meta: "textScore" } } ).limit(2)
SEE ALSO
$meta
122
copy
copied
db.articles.find(
{ author: "xyz", $text: { $search: "coffee bake" }
},
{ score: { $meta: "textScore" } }
).sort( { date: 1, score: { $meta: "textScore" } } )
123
$where
On this page
Definition
Behavior
o Available JavaScript Properties and Functions
o elemMatch
o Considerations
o JavaScript Enablement
Example
Definition
$where
copy
copied
{ $where: <string|JavaScript Code> }
NOTE
Starting in MongoDB 4.4, $where no longer supports the
deprecated BSON type JavaScript code with scope (BSON type
15). The $where operator only supports BSON type String (BSON
type 2) or BSON type JavaScript (BSON type 13). The use of BSON
type JavaScript with scope for $where has been deprecated since
MongoDB 4.2.1.
AGGREGATION ALTERNATIVES PREFERRED
124
Starting in MongoDB 3.6, the $expr operator allows the use
of aggregation expressions within the query language. And,
starting in MongoDB 4.4, the $function and $accumulator allows
users to define custom aggregation expressions in JavaScript if
the provided pipeline operators cannot fulfill your application’s
needs.
Given the available aggregation operators:
Behavior
125
Available Properties Available Functions
DBRef() NumberLong()
doassert() ObjectId()
emit() print()
gc() printjson()
HexData() printjsononeline()
hex_md5() sleep()
isNumber() Timestamp()
isObject() tojson()
ISODate() tojsononeline()
isString() tojsonObject()
UUID()
version()
elemMatch
126
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
JavaScript Enablement
127
In earlier versions, MongoDB does not allow JavaScript
execution on mongos instances.
Example
copy
copied
db.players.insertMany([
{ _id: 12378, name: "Steve", username: "steveisawe
some", first_login: "2017-01-01" },
{ _id: 2, name: "Anya", username: "anya", first_lo
gin: "2001-02-02" }
])
copy
copied
db.players.find( { $where: function() {
return (hex_md5(this.name) == "9b53e667f30cd329dca
1ec9e6a83e994")
} } );
copy
copied
{
"_id" : 2,
"name" : "Anya",
"username" : "anya",
128
"first_login" : "2001-02-02"
}
copy
copied
db.players.find( {$expr: { $function: {
body: function(name) { return hex_md5(name) ==
"9b53e667f30cd329dca1ec9e6a83e994"; },
args: [ "$name" ],
lang: "js"
} } } )
129
Geospatial Query Operators
On this page
Operators
NOTE
For details on specific operator, including syntax and examples, click
on the specific operator to go to its reference page.
Operators
Query Selectors
Name Description
130
Name Description
Geometry Specifiers
Name Description
131
Name Description
132
$geoIntersects
On this page
Definition
Behavior
Examples
Definition
$geoIntersects
copy
copied
{
<location field>: {
$geoIntersects: {
$geometry: {
type: "<GeoJSON object type>" ,
coordinates: [ <coordinates> ]
}
}
}
}
133
For $geoIntersects queries that specify GeoJSON geometries
with areas greater than a single hemisphere, the use of the
default CRS results in queries for the complementary
geometries.
copy
copied
{
<location field>: {
$geoIntersects: {
$geometry: {
type: "Polygon" ,
coordinates: [ <coordinates> ],
crs: {
type: "name",
properties: { name: "urn:x-mongodb:cr
s:strictwinding:EPSG:4326" }
}
}
}
}
}
IMPORTANT
134
If specifying latitude and longitude coordinates, list
the longitude first and then latitude:
Behavior
Geospatial Indexes
Degenerate Geometry
“Big” Polygons
Examples
Intersects a Polygon
135
The following example uses $geoIntersects to select
all loc data that intersect with the Polygon defined by
the coordinates array. The area of the polygon is less than the
area of a single hemisphere:
copy
copied
db.places.find(
{
loc: {
$geoIntersects: {
$geometry: {
type: "Polygon" ,
coordinates: [
[ [ 0, 0 ], [ 3, 6 ], [ 6, 1 ], [ 0, 0
] ]
]
}
}
}
}
)
copy
copied
db.places.find(
{
136
loc: {
$geoIntersects: {
$geometry: {
type : "Polygon",
coordinates: [
[
[ -100, 60 ], [ -100, 0 ], [ -100, -
60 ], [ 100, -60 ], [ 100, 60 ], [ -100, 60 ]
]
],
crs: {
type: "name",
properties: { name: "urn:x-mongodb:cr
s:strictwinding:EPSG:4326" }
}
}
}
}
}
)
137
$geoWithin
On this page
Definition
Behavior
Examples
Definition
$geoWithin
copy
copied
{
<location field>: {
$geoWithin: {
$geometry: {
type: <"Polygon" or "MultiPolygon"> ,
coordinates: [ <coordinates> ]
}
}
138
}
}
copy
copied
{
<location field>: {
$geoWithin: {
$geometry: {
type: "Polygon" ,
coordinates: [ <coordinates> ],
crs: {
type: "name",
properties: { name: "urn:x-mongodb:cr
s:strictwinding:EPSG:4326" }
}
}
}
}
}
139
If querying for inclusion in a shape defined by legacy coordinate
pairs on a plane, use the following syntax:
copy
copied
{
<location field>: {
$geoWithin: { <shape operator>: <coordinates>
}
}
}
$box,
$polygon,
$center (defines a circle), and
$centerSphere (defines a circle on a sphere).
IMPORTANT
If you use longitude and latitude, specify coordinates in order
of longitude, latitude.
Behavior
Geospatial Indexes
Unsorted Results
140
Degenerate Geometry
“Big” Polygons
Examples
Within a Polygon
The following example selects all loc data that exist entirely
within a GeoJSON Polygon. The area of the polygon is less than
the area of a single hemisphere:
copy
copied
db.places.find(
{
loc: {
$geoWithin: {
$geometry: {
type : "Polygon" ,
coordinates: [ [ [ 0, 0 ], [ 3, 6 ], [ 6
, 1 ], [ 0, 0 ] ] ]
}
}
}
141
}
)
copy
copied
db.places.find(
{
loc: {
$geoWithin: {
$geometry: {
type : "Polygon" ,
coordinates: [
[
[ -100, 60 ], [ -100, 0 ], [ -100, -
60 ], [ 100, -60 ], [ 100, 60 ], [ -100, 60 ]
]
],
crs: {
type: "name",
properties: { name: "urn:x-mongodb:cr
s:strictwinding:EPSG:4326" }
}
}
}
}
}
142
)
$within
143
$near
On this page
Definition
Behavior
Examples
Definition
$near
copy
copied
{
<location field>: {
$near: {
$geometry: {
type: "Point" ,
coordinates: [ <longitude> , <latitude> ]
},
144
$maxDistance: <distance in meters>,
$minDistance: <distance in meters>
}
}
}
copy
copied
{
$near: [ <x>, <y> ],
$maxDistance: <distance in radians>
}
145
the results to those documents that are at most the specified
distance from the center point.
Behavior
Sharded Collections
Sort Operation
SEE ALSO
2d Indexes and Geospatial Near Queries
Examples
146
IMPORTANT
If specifying latitude and longitude coordinates, list
the longitude first and then latitude:
copy
copied
db.places.find(
{
location:
{ $near :
{
$geometry: { type: "Point", coordinates:
[ -73.9667, 40.78 ] },
$minDistance: 1000,
$maxDistance: 5000
}
}
}
)
IMPORTANT
If specifying latitude and longitude coordinates, list
the longitude first and then latitude:
147
Valid longitude values are between -180 and 180, both
inclusive.
Valid latitude values are between -90 and 90, both inclusive.
copy
copied
db.legacy2d.find(
{ location : { $near : [ -73.9667, 40.78 ], $maxDi
stance: 0.10 } }
)
148
$nearSphere
On this page
Definition
Behavior
Examples
Definition
$nearSphere
copy
copied
149
$nearSphere: {
$geometry: {
type : "Point",
coordinates : [ <longitude>, <latitude> ]
},
$minDistance: <distance in meters>,
$maxDistance: <distance in meters>
}
}
copy
copied
{
$nearSphere: [ <x>, <y> ],
$minDistance: <distance in radians>,
$maxDistance: <distance in radians>
}
SEE ALSO
150
2d Indexes and Geospatial Near Queries
Behavior
Sharded Collections
Sort Operation
Examples
151
Then, the following example returns whose location is at
least 1000 meters from and at most 5000 meters from the
specified point, ordered from nearest to farthest:
copy
copied
db.places.find(
{
location: {
$nearSphere: {
$geometry: {
type : "Point",
coordinates : [ -73.9667, 40.78 ]
},
$minDistance: 1000,
$maxDistance: 5000
}
}
}
)
2d Index
copy
152
copied
db.legacyPlaces.find(
{ location : { $nearSphere : [ -73.9667, 40.78 ],
$maxDistance: 0.10 } }
)
2dsphere Index
copy
copied
db.legacyPlaces.find(
{ location : { $nearSphere : [ -73.9667, 40.78 ],
$minDistance: 0.0004 } }
)
153
$box
On this page
Definition
Behavior
Example
Definition
$box
To use the $box operator, you must specify the bottom left and
top right corners of the rectangle in an array object:
copy
copied
{
<location field>: {
$geoWithin: {
$box: [
[ <bottom left coordinates> ],
[ <upper right coordinates> ]
]
}
}
}
154
IMPORTANT
If you use longitude and latitude, specify longitude first.
Behavior
Example
The following example query returns all documents that are within
the box having points
at: [ 0 , 0 ], [ 0 , 100 ], [ 100 , 0 ],
and [ 100 , 100 ].
copy
copied
db.places.find( {
loc: { $geoWithin: { $box: [ [ 0, 0 ], [ 100, 100
] ] } }
} )
155
$center
On this page
Definition
Behavior
Example
Definition
$center
copy
copied
{
<location field>: {
$geoWithin: { $center: [ [ <x>, <y> ] , <radi
us> ] }
}
}
IMPORTANT
If you use longitude and latitude, specify longitude first.
156
Behavior
Example
copy
copied
db.places.find(
{ loc: { $geoWithin: { $center: [ [-74, 40.74], 10
] } } }
)
157
$centerSphere
On this page
Definition
Behavior
Example
Definition
$centerSphere
copy
copied
{
<location field>: {
$geoWithin: { $centerSphere: [ [ <x>, <y> ],
<radius> ] }
}
}
IMPORTANT
If you use longitude and latitude, specify longitude first.
Behavior
158
Applications can use $centerSphere without having a geospatial
index. However, geospatial indexes support much faster queries
than the unindexed equivalents.
Example
copy
copied
db.places.find( {
loc: { $geoWithin: { $centerSphere: [ [ -88, 30 ],
10/3963.2 ] } }
} )
159
$geometry
$geometry
copy
copied
$geometry: {
type: "<GeoJSON object type>",
coordinates: [ <coordinates> ]
}
copy
copied
$geometry: {
type: "Polygon",
coordinates: [ <coordinates> ],
crs: {
type: "name",
properties: { name: "urn:x-mongodb:crs:strict
winding:EPSG:4326" }
160
}
}
IMPORTANT
If specifying latitude and longitude coordinates, list
the longitude first and then latitude:
161
$maxDistance
On this page
Definition
Example
Definition
$maxDistance
Example
copy
copied
db.places.find( {
loc: { $near: [ -74 , 40 ], $maxDistance: 10 }
} )
162
$minDistance
On this page
Definition
Examples
Definition
$minDistance
Examples
IMPORTANT
If specifying latitude and longitude coordinates, list
the longitude first and then latitude:
163
Consider a collection places that has a 2dsphere index.
copy
copied
db.places.find(
{
location:
{ $near :
{
$geometry: { type: "Point", coordinates:
[ -73.9667, 40.78 ] },
$minDistance: 1000,
$maxDistance: 5000
}
}
}
)
copy
copied
db.places.find(
{
location: {
164
$nearSphere: {
$geometry: {
type : "Point",
coordinates : [ -73.9667, 40.78 ]
},
$minDistance: 1000,
$maxDistance: 5000
}
}
}
)
165
$polygon
On this page
Definition
Behavior
Example
Definition
$polygon
copy
copied
{
<location field>: {
$geoWithin: {
$polygon: [ [ <x1> , <y1> ], [ <x2> , <y2>
], [ <x3> , <y3> ], ... ]
}
}
}
The last point is always implicitly connected to the first. You can
specify as many points, i.e. sides, as you like.
IMPORTANT
If you use longitude and latitude, specify longitude first.
166
Behavior
Example
copy
copied
db.places.find(
{
loc: {
$geoWithin: { $polygon: [ [ 0 , 0 ], [ 3 , 6 ]
, [ 6 , 0 ] ] }
}
}
)
167
$uniqueDocs
On this page
Definition
Definition
$uniqueDocs
168
Array Query Operators
NOTE
For details on specific operator, including syntax and examples, click
on the specific operator to go to its reference page.
Name Description
Query an Array
Query an Array of Embedded Documents
169
$all
On this page
Behavior
Examples
Additional Examples
$all
copy
copied
{ <field>: { $all: [ <value1> , <value2> ... ] } }
Behavior
copy
copied
{ tags: { $all: [ "ssl" , "security" ] } }
is equivalent to:
copy
copied
{ $and: [ { tags: "ssl" }, { tags: "security" } ] }
170
Nested Array
copy
copied
db.articles.find( { tags: { $all: [ [ "ssl", "securit
y" ] ] } } )
copy
copied
db.articles.find( { $and: [ { tags: [ "ssl", "securit
y" ] } ] } )
copy
copied
db.articles.find( { tags: [ "ssl", "security" ] } )
copy
copied
tags: [ [ "ssl", "security" ], ... ]
tags: [ "ssl", "security" ]
171
The $all expression with a single element is for illustrative purposes
since the $all expression is unnecessary if matching only a single
[1]
element. Instead, when matching a single element, a “contains”
expression (i.e. arrayField: element ) is more suitable.
Examples
copy
copied
{
_id: ObjectId("5234cc89687ea597eabee675"),
code: "xyz",
tags: [ "school", "book", "bag", "headphone", "app
liance" ],
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" }
]
172
}
{
_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" }
]
}
copy
copied
db.inventory.find( { tags: { $all: [ "appliance", "sc
hool", "book" ] } } )
173
copy
copied
{
_id: ObjectId("5234cc89687ea597eabee675"),
code: "xyz",
tags: [ "school", "book", "bag", "headphone", "app
liance" ],
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" }
]
}
copy
copied
174
db.inventory.find( {
qty: { $all: [
{ "$elemMatch" :
{ size: "M", num: { $gt: 50} } },
{ "$elemMatch" :
{ num : 100, color: "green" } }
] }
} )
copy
copied
{
"_id" : ObjectId("5234ccb7687ea597eabee677"),
"code" : "efg",
"tags" : [ "school", "book"],
"qty" : [
{ "size" : "S", "num" : 10, "color" : "b
lue" },
{ "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" }
]
}
175
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:
copy
copied
db.inventory.find( { "qty.num": { $all: [ 50 ] } } )
copy
copied
db.inventory.find( { "qty.num" : 50 } )
NOTE
In most cases, MongoDB does not treat arrays as sets. This
operator provides a notable exception to this approach.
Additional Examples
Query an Array
Query an Array of Embedded Documents
Query Documents
SEE ALSO
db.collection.find()
176
$elemMatch (query)
On this page
Definition
Behavior
Examples
Additional Examples
SEE ALSO
$elemMatch (projection)
Definition
$elemMatch
copy
copied
{ <field>: { $elemMatch: { <query1>, <query2>, ...
} } }
Behavior
177
Examples
Element Match
copy
copied
{ _id: 1, results: [ 82, 85, 88 ] }
{ _id: 2, results: [ 75, 88, 89 ] }
copy
copied
db.scores.find(
{ results: { $elemMatch: { $gte: 80, $lt: 85 } } }
)
copy
copied
{ "_id" : 1, "results" : [ 82, 85, 88 ] }
copy
copied
178
db.survey.insertMany( [
{ "_id": 1, "results": [ { "product": "abc", "scor
e": 10 },
{ "product": "xyz", "scor
e": 5 } ] },
{ "_id": 2, "results": [ { "product": "abc", "scor
e": 8 },
{ "product": "xyz", "scor
e": 7 } ] },
{ "_id": 3, "results": [ { "product": "abc", "scor
e": 7 },
{ "product": "xyz", "scor
e": 8 } ] },
{ "_id": 4, "results": [ { "product": "abc", "scor
e": 7 },
{ "product": "def", "scor
e": 8 } ] }
] )
copy
copied
db.survey.find(
{ results: { $elemMatch: { product: "xyz", score:
{ $gte: 8 } } } }
)
179
{ "product" : "xyz", "scor
e" : 8 } ] }
With $elemMatch:
copy
copied
db.survey.find(
{ results: { $elemMatch: { product: "xyz" } } }
)
Without $elemMatch:
copy
copied
db.survey.find(
{ "results.product": "xyz" }
)
With $elemMatch:
copy
180
copied
db.survey.find(
{ "results": { $elemMatch: { product: { $ne: "xyz"
} } } }
)
Without $elemMatch:
copy
copied
db.survey.find(
{ "results.product": { $ne: "xyz" } }
)
181
{ "_id" : 4, "results" : [ { "product" : "abc", "scor
e" : 7 },
{ "product" : "def", "scor
e" : 8 } ] }
Additional Examples
Query an Array
Query an Array of Embedded Documents
Query Documents
SEE ALSO
db.collection.find()
182
$size
On this page
Additional Examples
$size
copy
copied
db.collection.find( { field: { $size: 2 } } );
copy
copied
db.collection.find( { field: { $size: 1 } } );
183
Additional Examples
Query an Array
Query an Array of Embedded Documents
Query Documents
SEE ALSO
db.collection.find()
184
Bitwise Query Operators
NOTE
For details on specific operator, including syntax and examples, click
on the specific operator to go to its reference page.
Name Description
185
$bitsAllClear
On this page
Behavior
Examples
$bitsAllClear
Numeric Bitmask
186
You can provide a numeric bitmask to be matched against the
operand field. It must be representable as a non-negative 32-bit
signed integer. Otherwise, $bitsAllClear will return an error.
BinData Bitmask
You can also use an arbitrarily large BinData instance as a
bitmask.
Position List
If querying a list of bit positions, each <position> must be a
non-negative integer. Bit positions start at 0 from the least
significant bit. For example, the decimal number 254 would have
the following bit positions:
Bit Value 1 1 1 1 1 1 1 0
Position 7 6 5 4 3 2 1 0
Behavior
Indexes
Sign Extension
187
Numbers are sign extended. For
example, $bitsAllClear considers bit position 200 to be set for
the negative number -5, but bit position 200 to be clear for the
positive number +5.
copy
copied
db.collection.save({ x: BinData(0, "ww=="), binaryVal
ueofA: "11000011" })
Examples
copy
copied
db.collection.save({ _id: 1, a: 54, binaryValueofA: "
00110110" })
db.collection.save({ _id: 2, a: 20, binaryValueofA: "
00010100" })
db.collection.save({ _id: 3, a: 20.0, binaryValueofA:
"00010100" })
db.collection.save({ _id: 4, a: BinData(0, "Zg=="), b
inaryValueofA: "01100110" })
188
copy
copied
db.collection.find( { a: { $bitsAllClear: [ 1, 5 ] }
} )
copy
copied
{ "_id" : 2, "a" : 20, "binaryValueofA" : "00010100"
}
{ "_id" : 3, "a" : 20, "binaryValueofA" : "00010100"
}
Integer Bitmask
copy
copied
db.collection.find( { a: { $bitsAllClear: 35 } } )
copy
copied
{ "_id" : 2, "a" : 20, "binaryValueofA" : "00010100"
}
{ "_id" : 3, "a" : 20, "binaryValueofA" : "00010100"
}
BinData Bitmask
189
The following query uses the $bitsAllClear operator to test
whether field a has bits clear at positions 2 and 4 (the binary
representation of BinData(0, "ID==") is 00010100.
copy
copied
db.collection.find( { a: { $bitsAllClear: BinData(0,
"ID==") } } )
copy
copied
{ "_id" : 2, "a" : 20, "binaryValueofA" : "00010100"
}
{ "_id" : 3, "a" : 20, "binaryValueofA" : "00010100"
}
190
$bitsAllSet
On this page
Behavior
Examples
$bitsAllSet
Numeric Bitmask
191
You can provide a numeric bitmask to be matched against the
operand field. It must be representable as a non-negative 32-bit
signed integer. Otherwise, $bitsAllSet will return an error.
BinData Bitmask
You can also use an arbitrarily large BinData instance as a
bitmask.
Position List
If querying a list of bit positions, each <position> must be a
non-negative integer. Bit positions start at 0 from the least
significant bit. For example, the decimal number 254 would have
the following bit positions:
Bit Value 1 1 1 1 1 1 1 0
Position 7 6 5 4 3 2 1 0
Behavior
Indexes
Sign Extension
192
Numbers are sign extended. For example, $bitsAllSet considers
bit position 200 to be set for the negative number -5, but bit
position 200 to be clear for the positive number +5.
copy
copied
db.collection.save({ x: BinData(0, "ww=="), binaryVal
ueofA: "11000011" })
Examples
copy
copied
db.collection.save({ _id: 1, a: 54, binaryValueofA: "
00110110" })
db.collection.save({ _id: 2, a: 20, binaryValueofA: "
00010100" })
db.collection.save({ _id: 3, a: 20.0, binaryValueofA:
"00010100" })
db.collection.save({ _id: 4, a: BinData(0, "Zg=="), b
inaryValueofA: "01100110" })
copy
193
copied
db.collection.find( { a: { $bitsAllSet: [ 1, 5 ] } }
)
copy
copied
{ "_id" : 1, "a" : 54, "binaryValueofA" : "00110110"
}
{ "_id" : 4, "a" : BinData(0,"Zg=="), "binaryValueofA
" : "01100110" }
Integer Bitmask
copy
copied
db.collection.find( { a: { $bitsAllSet: 50 } } )
copy
copied
{ "_id" : 1, "a" : 54, "binaryValueofA" : "00110110"
}
BinData Bitmask
copy
194
copied
db.collection.find( { a: { $bitsAllSet: BinData(0, "M
C==") } } )
copy
copied
{ _id: 1, a: 54, binaryValueofA: "00110110" }
195
$bitsAnyClear
On this page
Behavior
Examples
$bitsAnyClear
Numeric Bitmask
196
You can provide a numeric bitmask to be matched against the
operand field. It must be representable as a non-negative 32-bit
signed integer. Otherwise, $bitsAnyClear will return an error.
BinData Bitmask
You can also use an arbitrarily large BinData instance as a
bitmask.
Position List
If querying a list of bit positions, each <position> must be a
non-negative integer. Bit positions start at 0 from the least
significant bit. For example, the decimal number 254 would have
the following bit positions:
Bit Value 1 1 1 1 1 1 1 0
Position 7 6 5 4 3 2 1 0
Behavior
Indexes
Sign Extension
197
Numbers are sign extended. For
example, $bitsAnyClear considers bit position 200 to be set for
the negative number -5, but bit position 200 to be clear for the
positive number +5.
copy
copied
db.collection.save({ x: BinData(0, "ww=="), binaryVal
ueofA: "11000011" })
Examples
copy
copied
db.collection.save({ _id: 1, a: 54, binaryValueofA: "
00110110" })
db.collection.save({ _id: 2, a: 20, binaryValueofA: "
00010100" })
db.collection.save({ _id: 3, a: 20.0, binaryValueofA:
"00010100" })
db.collection.save({ _id: 4, a: BinData(0, "Zg=="), b
inaryValueofA: "01100110" })
198
copy
copied
db.collection.find( { a: { $bitsAnyClear: [ 1, 5 ] }
} )
copy
copied
{ "_id" : 2, "a" : 20, "binaryValueofA" : "00010100"
}
{ "_id" : 3, "a" : 20.0, "binaryValueofA" : "00010100
" }
Integer Bitmask
copy
copied
db.collection.find( { a: { $bitsAnyClear: 35 } } )
copy
copied
{ "_id" : 1, "a" : 54, "binaryValueofA" : "00110110"
}
{ "_id" : 2, "a" : 20, "binaryValueofA" : "00010100"
}
{ "_id" : 3, "a" : 20.0, "binaryValueofA" : "00010100
" }
{ "_id" : 4, "a" : BinData(0,"Zg=="), "binaryValueofA
" : "01100110" }
199
BinData Bitmask
copy
copied
db.collection.find( { a: { $bitsAnyClear: BinData(0,
"MC==") } } )
copy
copied
{ "_id" : 2, "a" : 20, "binaryValueofA" : "00010100"
}
{ "_id" : 3, "a" : 20.0, "binaryValueofA" : "00010100
" }
{ "_id" : 4, "a" : BinData(0,"Zg=="), "binaryValueofA
" : "01100110" }
200
$bitsAnySet
On this page
Behavior
Examples
$bitsAnySet
Numeric Bitmask
201
You can provide a numeric bitmask to be matched against the
operand field. It must be representable as a non-negative 32-bit
signed integer. Otherwise, $bitsAnySet will return an error.
BinData Bitmask
You can also use an arbitrarily large BinData instance as a
bitmask.
Position List
If querying a list of bit positions, each <position> must be a
non-negative integer. Bit positions start at 0 from the least
significant bit. For example, the decimal number 254 would have
the following bit positions:
Bit Value 1 1 1 1 1 1 1 0
Position 7 6 5 4 3 2 1 0
Behavior
Indexes
Sign Extension
202
Numbers are sign extended. For example, $bitsAnySet considers
bit position 200 to be set for the negative number -5, but bit
position 200 to be clear for the positive number +5.
copy
copied
db.collection.save({ x: BinData(0, "ww=="), binaryVal
ueofA: "11000011" })
Examples
copy
copied
db.collection.save({ _id: 1, a: 54, binaryValueofA: "
00110110" })
db.collection.save({ _id: 2, a: 20, binaryValueofA: "
00010100" })
db.collection.save({ _id: 3, a: 20.0, binaryValueofA:
"00010100" })
db.collection.save({ _id: 4, a: BinData(0, "Zg=="), b
inaryValueofA: "01100110" })
copy
203
copied
db.collection.find( { a: { $bitsAnySet: [ 1, 5 ] } }
)
copy
copied
{ "_id" : 1, "a" : 54, "binaryValueofA" : "00110110"
}
{ "_id" : 4, "a" : BinData(0,"Zg=="), "binaryValueofA
" : "01100110" }
Integer Bitmask
copy
copied
db.collection.find( { a: { $bitsAnySet: 35 } } )
copy
copied
{ "_id" : 1, "a" : 54, "binaryValueofA" : "00110110"
}
{ "_id" : 4, "a" : BinData(0,"Zg=="), "binaryValueofA
" : "01100110" }
BinData Bitmask
copy
copied
{ "_id" : 1, "a" : 54, "binaryValueofA" : "00110110"
}
{ "_id" : 2, "a" : 20, "binaryValueofA" : "00010100"
}
{ "_id" : 3, "a" : 20.0, "binaryValueofA" : "00010100
" }
{ "_id" : 4, "a" : BinData(0,"Zg=="), "binaryValueofA
" : "01100110" }
205
$comment
On this page
Definition
Behavior
Examples
Definition
$comment
copy
copied
db.collection.find( { <query>, $comment: <comment>
} )
Behavior
You can use the $comment with any expression taking a query
predicate, such as the query predicate
in db.collection.update() or in the $match stage of
the aggregation pipeline. For an example, see Attach a Comment
to an Aggregation Expression.
206
Examples
copy
copied
db.records.find(
{
x: { $mod: [ 2, 0 ] },
$comment: "Find even values."
}
)
{
"op" : "query",
"ns" : "test.records",
"command" : {
"find" : "records",
"filter" : {
"x" : {
"$mod" : [
2,
0
]
},
"$comment" : "Find even values."
},
"comment" : "Find even values.",
...
207
Comments also appear in the MongoDB log if the database profiler
level is set to 2 and slowms is set to 0ms.
This db.setProfilingLevel() command sets these two
parameters:
copy
copied
db.setProfilingLevel(2, 0)
{"t":{"$date":"2020-09-17T11:32:20.415-07:00"},"s":"I
",
"c":"COMMAND", "id":51803, "ctx":"conn7","msg":"Sl
ow query",
"attr":{"type":"command","ns":"test.records","appName
":"MongoDB
Shell","command":{"find":"records","filter":{"x":{"$m
od":[2.0,0.0]},
"$comment":"Find even values."},"comment":"Find even
values."
...
You can use the $comment with any expression taking a query
predicate.
copy
copied
db.records.aggregate( [
{ $match: { x: { $gt: 0 }, $comment: "Don't allow
negative inputs." } },
208
{ $group : { _id: { $mod: [ "$x", 2 ] }, total: {
$sum: "$x" } } }
] )
209
Projection Operators
NOTE
find() operations on views do not support the
following projection operators:
$
$elemMatch
$slice
$meta
NOTE
For details on specific operator, including syntax and examples, click
on the specific operator to go to its reference page.
Name Description
210
Name Description
211
$ (projection)
On this page
Definition
Usage Considerations
Behavior
Examples
Further Reading
Definition
DISAMBIGUATION
To specify an array element to update, see the positional $
operator for updates.
Usage Considerations
212
Both the $ operator and the $elemMatch operator project
the first matching element from an array based on a condition.
The $ operator projects the first matching array element from each
document in a collection based on some condition from the query
statement.
Behavior
Syntax
To return the first array element that matches the specified query
condition on the array:
copy
copied
db.collection.find( { <array>: <condition> ... },
{ "<array>.$": 1 } )
db.collection.find( { <array.field>: <condition> ...}
,
{ "<array>.$": 1 } )
copy
213
copied
db.collection.find( { <someOtherArray>: <condition> .
.. },
{ "<array>.$" : 1 } )
IMPORTANT
To ensure expected behavior, the arrays used in the query
document and the projection document must be the same length.
If the arrays are different lenghts, the operation may error in
certain scenarios.
copy
copied
214
query returns the first document inside a grades array that
has a mean of greater than 70 and a grade of greater than 90.
copy
copied
215
For example, starting in MongoDB 4.4, the following operation is
invalid:
db.inventory.find( { }, { "instock.$.qty": 1 } ) // I
nvalid starting in 4.4
Examples
216
Project Array Values
copy
copied
{ "_id" : 1, "semester" : 1, "grades" : [ 70, 87, 90
] }
{ "_id" : 2, "semester" : 1, "grades" : [ 90, 88, 92
] }
{ "_id" : 3, "semester" : 1, "grades" : [ 85, 100, 90
] }
{ "_id" : 4, "semester" : 2, "grades" : [ 79, 85, 80
] }
{ "_id" : 5, "semester" : 2, "grades" : [ 88, 88, 92
] }
{ "_id" : 6, "semester" : 2, "grades" : [ 95, 90, 96
] }
copy
copied
db.students.find( { semester: 1, grades: { $gte: 85 }
},
{ "grades.$": 1 } )
copy
copied
{ "_id" : 1, "grades" : [ 87 ] }
{ "_id" : 2, "grades" : [ 90 ] }
{ "_id" : 3, "grades" : [ 85 ] }
217
Although the array field grades may contain multiple elements
that are greater than or equal to 85, the $ projection operator
returns only the first matching element from the array.
copy
copied
{ "_id" : 7, semester: 3, "grades" : [ { grade: 80, m
ean: 75, std: 8 },
{ grade: 85, m
ean: 90, std: 5 },
{ grade: 90, m
ean: 85, std: 3 } ] }
copy
copied
db.students.find(
{ "grades.mean": { $gt: 70 } },
{ "grades.$": 1 }
)
218
The operation returns the following documents:
copy
copied
{ "_id" : 7, "grades" : [ { "grade" : 80, "mean" :
75, "std" : 8 } ] }
{ "_id" : 8, "grades" : [ { "grade" : 92, "mean" :
88, "std" : 8 } ] }
219
$elemMatch (projection)
SEE ALSO
$elemMatch (query)
On this page
Definition
Usage Considerations
Examples
Definition
$elemMatch
Usage Considerations
Returned Element
The $ operator projects the first matching array element from each
document in a collection based on some condition from the query
statement.
220
Field Order
copy
copied
db.players.insert( {
name: "player1",
games: [ { game: "abc", score: 8 }, { game: "xyz",
score: 5 } ],
joined: new Date("2020-01-01"),
lastLogin: new Date("2020-05-01")
} )
copy
copied
db.players.find( {}, { games: { $elemMatch: { score:
{ $gt: 5 } } }, joined: 1, lastLogin: 1 } )
{
"_id" : ObjectId("5edef64a1c099fff6b033977"),
"joined" : ISODate("2020-01-01T00:00:00Z"),
"lastLogin" : ISODate("2020-05-01T00:00:00Z"),
"games" : [ { "game" : "abc", "score" : 8 } ]
}
221
In version 4.2 and earlier, the $elemMatch projection of an
existing field upholds the ordering in the document:
{
"_id" : ObjectId("5edef91e76ddff7d92f118e1"),
"games" : [ { "game" : "abc", "score" : 8 } ],
"joined" : ISODate("2020-01-01T00:00:00Z"),
"lastLogin" : ISODate("2020-05-01T00:00:00Z")
}
Restrictions
Examples
copy
copied
{
_id: 1,
zipcode: "63109",
students: [
{ name: "john", school: 102, age: 10 },
{ name: "jess", school: 102, age: 11 },
{ name: "jeff", school: 108, age: 15 }
]
}
{
_id: 2,
zipcode: "63110",
students: [
222
{ name: "ajax", school: 100, age: 7 },
{ name: "achilles", school: 100, age: 8
},
]
}
{
_id: 3,
zipcode: "63109",
students: [
{ name: "ajax", school: 100, age: 7 },
{ name: "achilles", school: 100, age: 8
},
]
}
{
_id: 4,
zipcode: "63109",
students: [
{ name: "barney", school: 102, age: 7 }
,
{ name: "ruth", school: 102, age: 16 },
]
}
Zipcode Search
copy
copied
db.schools.find( { zipcode: "63109" },
223
{ students: { $elemMatch: { school:
102 } } } )
copy
copied
{ "_id" : 1, "students" : [ { "name" : "john", "schoo
l" : 102, "age" : 10 } ] }
{ "_id" : 3 }
{ "_id" : 4, "students" : [ { "name" : "barney", "sch
ool" : 102, "age" : 7 } ] }
copy
copied
db.schools.find( { zipcode: "63109" },
224
{ students: { $elemMatch: { school:
102, age: { $gt: 10} } } } )
copy
copied
{ "_id" : 1, "students" : [ { "name" : "jess", "schoo
l" : 102, "age" : 11 } ] }
{ "_id" : 3 }
{ "_id" : 4, "students" : [ { "name" : "ruth", "schoo
l" : 102, "age" : 16 } ] }
SEE ALSO
$ (projection) operator
225
$slice (projection)
On this page
Definition
Syntax
Behavior
Examples
Definition
$slice
DISAMBIGUATION
For information on limiting the size of an array during an update
with $push, see the $slice modifier instead.
For aggregation operator, see $slice aggregation operator
instead.
Syntax
copy
copied
db.collection.find(
<query>,
{ <arrayField>: { $slice: <number> } }
);
or
226
copy
copied
db.collection.find(
<query>,
{ <arrayField>: { $slice: [ <number>, <number> ] }
}
);
Value Description
Specify a
positive
number n to
return the
$slice: <number> first n elements.
Specify a
negative
number n to
return the
last n elements.
If the <number> is
greater than the
number of array
elements, the query
returns all array
227
Value Description
elements.
For
$slice: [ <number to skip>, <number the <number to sk
to return> ] ip>:
Specify a
positive
number n to
skip n elements
from the start
of the array; i.e.
0th index
position. Based
on a zero-based
array
index, 1 indicat
es the starting
228
Value Description
position of the
2nd element,
etc. If n is
greater than the
number of
array elements,
the query
returns an
empty array for
the <arrayFi
eld>.
Specify a
negative
number n to
skip
backward n ele
ments from the
start of the
array; i.e. 0th
index position
Based on a
zero-based
array index (i.e.
the first element
is at index 0), -
1 indicates the
starting
position of the
last element,
etc. If the
absolute value
229
Value Description
of the negative
number is
greater than the
number of
array elements,
the starting
position is the
start of the
array.
For
the <number to re
turn>, you must
specify
a positive number n to
return the
next n elements,
starting after
skipping the specified
number.
Behavior
230
For example, consider a collection inventory with documents
that contain a size field:
copy
copied
db.inventory.find( { }, { qty: 1, "details.colors": {
$slice: 1 } } )
copy
copied
db.inventory.find( { }, { _id: 0, "details.colors": {
$slice: 1 } } )
{ "item" : "socks", "qty" : 100, "details" : { "color
s" : [ "blue" ], "sizes" : [ "S", "M", "L" ] } }
231
In previous versions, the $slice projection also include the other
fields in the nested document regardless of whether the projection
is an inclusion or an exclusion.
View Restriction
SEE ALSO
Projection
Examples
copy
copied
db.posts.insertMany([
{
_id: 1,
title: "Bagels are not croissants.",
comments: [ { comment: "0. true" }, { comment: "
1. croissants aren't bagels."} ]
},
233
{
_id: 2,
title: "Coffee please.",
comments: [ { comment: "0. fooey" }, { comment:
"1. tea please" }, { comment: "2. iced coffee" }, { c
omment: "3. cappuccino" }, { comment: "4. whatever" }
]
}
])
copy
copied
db.posts.find( {}, { comments: { $slice: 3 } } )
copy
copied
{
"_id" : 1,
"title" : "Bagels are not croissants.",
"comments" : [ { "comment" : "0. true" }, { "comme
nt" : "1. croissants aren't bagels." } ]
}
{
"_id" : 2,
"title" : "Coffee please.",
234
"comments" : [ { "comment" : "0. fooey" }, { "comm
ent" : "1. tea please" }, { "comment" : "2. iced coff
ee" } ]
}
copy
copied
db.posts.find( {}, { comments: { $slice: -3 } } )
copy
copied
{
"_id" : 1,
"title" : "Bagels are not croissants.",
"comments" : [ { "comment" : "0. true" }, { "comme
nt" : "1. croissants aren't bagels." } ]
}
{
"_id" : 2,
"title" : "Coffee please.",
"comments" : [ { "comment" : "2. iced coffee" }, {
"comment" : "3. cappuccino" }, { "comment" : "4. what
ever" } ]
}
235
The following operation uses the $slice projection operator on
the comments array to:
Skip the first element such that the second element is the
starting point.
Then, return three elements from the starting point.
If the array has less than three elements after the skip, all
remaining elements are returned.
copy
copied
db.posts.find( {}, { comments: { $slice: [ 1, 3 ] } }
)
copy
copied
{
"_id" : 1,
"title" : "Bagels are not croissants.",
"comments" : [ { "comment" : "1. croissants aren't
bagels." } ]
}
{
"_id" : 2,
"title" : "Coffee please.",
"comments" : [ { "comment" : "1. tea please" }, {
"comment" : "2. iced coffee" }, { "comment" : "3. cap
puccino" } ]
}
236
The following operation uses the $slice projection operator on
the comments array to
Skip backwards from the first element such that the last
element is the starting point.
Then, return three elements from the starting point.
If the array has less than three elements after the skip, all
remaining elements in the array are returned.
copy
copied
db.posts.find( {}, { comments: { $slice: [ -1, 3 ] }
} )
copy
copied
{
"_id" : 1,
"title" : "Bagels are not croissants.",
"comments" : [ { "comment" : "1. croissants aren't
bagels." } ]
}
{
"_id" : 2,
"title" : "Coffee please.",
"comments" : [ { "comment" : "4. whatever" } ]
}
237