Database Reference
In-Depth Information
If you're querying from an environment that doesn't support a native regex type, you
can use the special $regex and $options operators. Using these operators from the
shell, you can express the query in yet another way:
db.reviews.find({user_id: ObjectId("4c4b1476238d3b4dd5000001"),
text: {$regex: "best|worst", $options: "i" })
M ISCELLANEOUS QUERY OPERATORS
Two mo re quer y operat ors aren't easily categorized and thus dese r ve their o wn sec -
tion. The first is $mod , which allows you to query documents matching a given modulo
operation. For instance, you can find all order subtotals that are evenly divisible by 3
using the following query:
db.orders.find({subtotal: {$mod: [3, 0]}})
You can see that the $mod operator takes an array having two values. The first is the
divisor and the second is the expected remainder. Thus, this query technically reads,
“Find all documents with subtotals that return a remainder of 0 when divided by 3.”
This is a contrived example, but it demonstrates the idea. If you end up using the $mod
operator, keep in mind that it won't use an index.
The second miscellaneous operator is the $type operator, which matches values by
their BSON type. I don't recommend storing multiple types for the same field within a
collection, but if the situation ever arises, you have a query operator that essentially
lets you test against type. This came in handy recently when I discovered a user whose
_id queries weren't always matching when they should. The problem was that the user
had been storing IDs as both strings and as proper object ID s. These are represented
as BSON types 2 and 7, respectively, and to a new user, the distinction is easy to miss.
Correcting the issue first required finding all documents with ids stored as strings.
The $type operator can help do just that:
db.users.find({_id: {$type: 2}})
5.2.2
Query options
All queries require a query selector. Even if empty, the query selector essentially
defines the query. But when issuing a query, you have a variety of query options to
choose from which allow you to further constrain the result set. I describe those
options here.
P ROJECTIONS
You can use a projection to select a subset of fields to return from each document in a
query result set. Especially in cases where you have large documents, using a projec-
tion will minimize the costs of network latency and deserialization. Projections are
most commonly defined as a set of fields to return:
db.users.find({}, {username: 1})
This query returns user documents excluding all but two fields: the username and the
_id field, which is always included by default.
Search WWH ::




Custom Search