CodeToLive

Querying Documents in MongoDB

Master MongoDB's query language and operators to efficiently retrieve data.

Basic Query Structure

db.collection.find(query, projection)

Equality Queries

// Find documents where status equals "A"
db.inventory.find({ status: "A" })

// Find documents where qty equals 50
db.inventory.find({ qty: 50 })

Comparison Operators

// $gt, $gte, $lt, $lte, $ne
db.inventory.find({ qty: { $gt: 20 } })

// $in, $nin
db.inventory.find({ status: { $in: ["A", "D"] } })

Logical Operators

// $and
db.inventory.find({
  $and: [
    { status: "A" },
    { qty: { $lt: 30 } }
  ]
})

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

Element Operators

// $exists
db.inventory.find({ qty: { $exists: true } })

// $type
db.inventory.find({ qty: { $type: "number" } })

Array Operators

// $all
db.inventory.find({ tags: { $all: ["red", "blank"] } })

// $size
db.inventory.find({ tags: { $size: 3 } })
← Back to Tutorials