MongoDB Basic Shell Commands (part-3)

MongoDB Basic Shell Commands (part-3)

MongoDB Basic Shell Commands (part-2)

Deleting Documents and Collections

deleteOne() and deleteMany()

Syntax : db.collection.deleteOne(<query>) and db.collection.deleteMany(<query>). The following command deletes all the documents that have test field equal to 1.

db.users.deleteMany({"test": 1})

The following command deletes one document that first matched the query i.e. that has a test field equal to 3.

db.users.deleteOne({ "test": 3 })

The following command deletes the users collection. Please be mindful, this operation cannot be undone.

db.users.drop()

Query Operator

Comparison

Syntax: { <field>: { <operator>: <value> }}

  • $eq = EQual to
  • $neq = Not EQual to
  • $gt = Greater Than
  • $lt = Less Than
  • $gte = Greater Than or Equal to
  • $lte = Less Than or Equal to

The following command finds all documents where the age was less than or equal to 30 and the usertype was not Subscriber:

db.users.find({ "age": { "$lte" : 30 },
                "usertype": { "$ne": "Subscriber" } }).pretty()

Look at the following two commands:

db.users.find({ "age": { "$lte" : 70 },
                "usertype": { "$eq": "Customer" }}).pretty()
db.users.find({ "age": { "$lte" : 70 },
                "usertype": "Customer" }).pretty()

They both are same. The first one is using a redundant equality operator, and the second one is using an implicit equality operator. In most cases, we use implicit equality operator.

Logic

  • $and => Match all the specified query clauses.
  • $or => At least one of the query clauses is matched.
  • $nor => Fail to match both given clauses.
  • $not => Negates the query requirement.

$and, $or and $nor have similar syntax: {<operator> : [{statement1}, {statement2},...]}.

$not has slightly different syntax: {"$not": {statement}}.

The following command finds all documents in the routes collection where airplanes CR2 or A81 left or landed in the KZN airport:

db.routes.find({ "$and": [ { "$or" :[ { "dst_airport": "KZN" },
                                    { "src_airport": "KZN" }
                                  ] },
                          { "$or" :[ { "airplane": "CR2" },
                                     { "airplane": "A81" } ] }
                         ]}).pretty()

$and is used as the default operator when an operator is not specified for more than one clause. Look at the following example where $and is implicit :

The most succinct query to return all documents from the inspections collection where the inspection date is either "Feb 20 2015", or "Feb 21 2015" and the company is not part of the "Cigarette Retail Dealer - 127" sector :

db.inspections.find(
  { "$or": [ { "date": "Feb 20 2015" },
             { "date": "Feb 21 2015" } ],
    "sector": { "$ne": "Cigarette Retail Dealer - 127" }}).pretty()

MongoDB Basic Shell Commands (part-4)

Thanks for reading, any correction or recommendation is welcome.