How to Query MongoDB Documents

db.inventory.insertMany([
   { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
   { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },
   { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
   { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
   { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }
]);

Finding ALL documents in a Collection

db.inventory.find( {} )

Finding a Single Match

db.inventory.findOne()

Finding SOME documents in a Collection

db.inventory.find( { status: "D" } )
db.inventory.find( { status: "D", item: "planner" } )

Finding SOME documents using OR

db.inventory.find(
  { $or: [
          { type: "Planner" },
          { type: "Notebook" }
         ]
  }
)
db.inventory.find(
  { $or: [
          { status: "A" },
          { type: "Notebook" }
         ]
  }
)

Finding SOME documents using RANGES

db.collection.find( { <field>: { $gt: <value1>, $lt: <value2> } } );
db.inventory.find( { status: "A", qty: { $lt: 30 } } )

Querying for properties IN a set

db.inventory.find( { status: { $in: ["A", "B", "C"] } } )
db.inventory.find( { type: { $in: ["Journal", "Notebook", "Paper"] } } )

Querying Nested Documents

db.inventory.find({ status: "A", size: { h: 14, w: 21, uom: "cm" } })
db.inventory.find({ "size.h": 14 });
db.inventory.find({ status: "A", "size.h": 14 })

Range Queries in Nested Documents

{
    "_id" : ObjectId("5b631aff2f6ff13721a2e38b"),
    "item" : "journal",
    "status" : "A",
    "size" : {
        "h" : 14,
        "w" : 21,
        "uom" : "cm"
    }
}
db.inventory.find({ "size.h":  { $gt: 10 } })
db.inventory.find({ "size.h":  { $gt: 10, $lt: 100 } })

Range Queries in Nested Documents using OR

db.inventory.find( {
     status: "A",
     $or: [
            { qty: { $lt: 30 } },
            { "size.h": { $gt: 10 } }
          ]
    }
)

List of Comparisons for Ranges

Name Description
$eq Matches values that are equal to a specified value.
$gt Matches values that are greater than a specified value.
$gte Matches values that are greater than or equal to a specified value
$in Matches any of the values specified in an array
$lt Matches values that are less than 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.
$nin Matches none of the values specified in an array.

 Previous Lesson Next Lesson 

Outline

[menu]

/