MongoDb Read
1 db.coll.findOne() // returns a single document
2 db.coll.find() // returns a cursor - show 20 results - "it" to display more
3 db.coll.find().pretty()
4 db.coll.find({name: "Max", age: 32}) // implicit logical "AND".
5 db.coll.find({date: ISODate("2020-09-25T13:57:17.180Z")})
6 db.coll.find({name: "Max", age: 32}).explain("executionStats") // or "queryPlanner" or "allPlansExecution"
7 db.coll.distinct("name")
8
9 // Count
10 db.coll.count({age: 32}) // estimation based on collection metadata
11 db.coll.estimatedDocumentCount() // estimation based on collection metadata
12 db.coll.countDocuments({age: 32}) // alias for an aggregation pipeline - accurate count
13
14 // Comparison
15 db.coll.find({"year": {$gt: 1970}})
16 db.coll.find({"year": {$gte: 1970}})
17 db.coll.find({"year": {$lt: 1970}})
18 db.coll.find({"year": {$lte: 1970}})
19 db.coll.find({"year": {$ne: 1970}})
20 db.coll.find({"year": {$in: [1958, 1959]}})
21 db.coll.find({"year": {$nin: [1958, 1959]}})
22
23 // Logical
24 db.coll.find({name:{$not: {$eq: "Max"}}})
25 db.coll.find({$or: [{"year" : 1958}, {"year" : 1959}]})
26 db.coll.find({$nor: [{price: 1.99}, {sale: true}]})
27 db.coll.find({
28 $and: [
29 {$or: [{qty: {$lt :10}}, {qty :{$gt: 50}}]},
30 {$or: [{sale: true}, {price: {$lt: 5 }}]}
31 ]
32 })
33
34 // Element
35 db.coll.find({name: {$exists: true}})
36 db.coll.find({"zipCode": {$type: 2 }})
37 db.coll.find({"zipCode": {$type: "string"}})
38
39 // Aggregation Pipeline
40 db.coll.aggregate([
41 {$match: {status: "A"}},
42 {$group: {_id: "$cust_id", total: {$sum: "$amount"}}},
43 {$sort: {total: -1}}
44 ])
45
46 // Text search with a "text" index
47 db.coll.find({$text: {$search: "cake"}}, {score: {$meta: "textScore"}}).sort({score: {$meta: "textScore"}})
48
49 // Regex
50 db.coll.find({name: /^Max/}) // regex: starts by letter "M"
51 db.coll.find({name: /^Max$/i}) // regex case insensitive
52
53 // Array
54 db.coll.find({tags: {$all: ["Realm", "Charts"]}})
55 db.coll.find({field: {$size: 2}}) // impossible to index - prefer storing the size of the array & update it
56 db.coll.find({results: {$elemMatch: {product: "xyz", score: {$gte: 8}}}})
57
58 // Projections
59 db.coll.find({"x": 1}, {"actors": 1}) // actors + _id
60 db.coll.find({"x": 1}, {"actors": 1, "_id": 0}) // actors
61 db.coll.find({"x": 1}, {"actors": 0, "summary": 0}) // all but "actors" and "summary"
62
63 // Sort, skip, limit
64 db.coll.find({}).sort({"year": 1, "rating": -1}).skip(10).limit(3)
65
66 // Read Concern
67 db.coll.find().readConcern("majority")