CHAPTER 3Queries
Filters
Filters are objects with special fields starting with $
which represent comparison operators. This notation takes a bit of time to get used to, but it is really convenient, since it matches the structure of the documents themselves.
$eq | Equals |
$gt | Greater than |
$gte | Greater than or equal |
$lt | Less than |
$lte | Less than or equal |
$ne | Not equal |
$in | Any of the values in an array |
$nin | None of the values in an array |
$and | Logical AND |
$or | Logical OR |
$not | Logical NOT |
$nor | Fail to match both sides |
$exists | Certain field exists |
$type | Certain field has a certain type |
$all | Array contains all elements |
$size | Array has certain size |
Some examples:
{ name: "pauek" } // name = "pauek"
{ age: { $gt: 20 } } // age > 20
{ status: { $in: ["A", "B"] } } // status IN ("A", "B")
{ $and: [{ a: { $gte: 1 } }, { b: "two" }] } // a >= 1 AND b = 'two'
{ $or: [{ a: { $lt: 1 } }, { b: "two" }]} // a < 1 OR b = 'two'
{ $not: { $or: [{ a: 1 }, { b: "two" }] } } // NOT (a = 1 OR b = 'two')
{ name: /^z/ } // name LIKE 'z%'
{ "position.coords.x": { $gt: 10 } } // position.coords.x > 10
{ tags: "jazz" } // tags contains "jazz"
{ tags: ["jazz", "indie"] } // tags = ["jazz", "indie"]
{ tags: { $all: ["classical", "popular"] } } // has all tags mentioned
{
place: /land$/,
coords: { x: { $gt: 10 }, y: { $lt: 10 } } // querying subdocs
}
Find
findOne
looks for the first document matching the query parameter:
db.users.findOne({ isChild: true });
{
"_id": ObjectId("5ee9fa446b327281a5213f44"),
"username": "zipi",
"age": 9
}
find
returns a cursor for the whole sequence of documents matching a certain query:
db.users.find({ name: { $regex: "^z" } });
{
"_id": ObjectId("5ee9fa446b327281a5213f44"),
"username": "zipi",
"age": 9
}
{
"_id": ObjectId("5ee9fa446b327281a5213f45"),
"username": "zape",
"age": 9
}
find
and findOne
return a cursor, an object which can produce a sequence of the results of a query. Within the Mongo Shell, cursors are iterated automatically and the documents shown on screen. Cursors have methods to alter the result of the search and filter, sort, limit, etc.
Sorting
The sort
method can be applied to the result of find
, and receives an object specifying what fields to order by.
Some examples:
db.users.find().sort({ name: 1 }); // Ascending
db.users.find().sort({ age: -1 }); // Descending
db.users.find().sort({
// Two criteria
username: 1,
age: -1,
});
Projecting
To choose what fields to retrieve from each document you can use projection
. The projection is an object which selects which fields to return by setting them to 1:
db.users.find({}, { name: 1 }); // Only the `name` field
db.users.find({ age: { $gte: 5 } }, { age: 1 }); // Only the `age`
db.users.find({}).projection({ name: 1 }); // project afterwards
Distinct values
distinct
returns all the different salues (similar to SELECT DISTINCT
in SQL).
db.users.distinct("age"); // distinct ages
db.users.distinct("age", { age: { $gte: 5 } }); // distinct ages > 10
Paging
To limit
results to 20 documents:
db.users.find().limit(20); // First page of 20 results
db.users.find().skip(20).limit(20); // Second page of 20 results
db.users.find().skip(40).limit(20); // Third page of 20 results
// ...