MongoDB Commands Cheatsheet list: 1. MongoDB Commands Listing (Common Line Options): There are numerous options provided by MongoDB but in this section, let us discuss the most common options of MongoDB when used in conjunction with the MongoDB shell startup, to work with MongoDB database server seamlessly. Mongo Shell Command History¶. You can retrieve previous commands issued in the mongo shell with the up and down arrow keys. Command history is stored in /.dbshell file. See.dbshell for more information. Command Line Options¶. The mongo shell can be started with numerous options. See mongo shell page for details on all available options. The following table displays some common options for. Question: What is SQL injection? Answer: SQL injection is a code injection technique used to hack data-driven applications. Question: What are views, and why are they used? Answer: SQL views are virtual tables created from one or more tables. Views are a subset of data; hence, it can limit the degree of exposure of data from the tables. MongoDB Cheat Sheet Show All Databases show dbs Show Current Database db Create Or Switch Database use acme Drop db.dropDatabase Create Collection db.createCollection('posts') Show Collections show collections Insert Row.
/Title: MongoDB Query Operator Cheat SheetMeta Description: This MongoDB query operator cheat sheet provides a quick coding reference.Meta Keywords: MongoDB Query OperatorAuthor: orkbTemplate: Unstructured TutorialCategories: MongoDBTags: MongoDB, MongoDB query operator cheat sheetStatus:ID: 247/
Introduction
The MongoDB document database is a receptive repository for many documents. You want to find results that match your customized search criteria. One main key to accomplishing this task successfully is to use the appropriate query operator. With this MongoDB query operator cheat sheet, you’ll be able to do just that in record time.
Comparison Query Operators
Some MongoDB query operators help you to search documents that omit certain values.
An example is shown here where the
$nin
operator that returns documents in a collection called family. The documents have an age field. In that field, any age but 2 or 8 will be returned in the results. If any document doesn’t have an age field, it will be returned as well.
| Name | Description | Usage |
|:—–|:————|:—–:|
|$nin | Matches none of the values specified in an array.| db.family.find( { age: { $nin: [ 2, 8 ] } } )
- The
$ne
operator shown in the example below returns different documents in the same family collection. The values it will omit are those that are female in the gender field. Use $ne when you want to search results that find all but those documents that are without a particular value you specify.
db.family.find( { gender: { $ne: 'female' } } )
- In this example, the
$lte
operator will return results that have values of 17 or less found in the age field.
db.family.find( { age: { $lte: 17 } } )
- The
$in
operator will look for equal values that match anything you specify in an array.
{ field: { $in: [<value1>, <value2>, .. <valuen> ] } }
- The
$eq
operator match returns results that are exactly the same as the value you specify.
{ <field>: { $eq: <value> } }
The
$gte
operator searches for values greater than a value that is specified.The example here shows the family collection as the database where documents in the gender field with a value or 7 or more are searched.
db.family.find( { gender: { $gt: 7 } } )
Array Query Operators
The
$elemMatch
operator returns documents if values match all specified conditions.The example below
find()
operator looks for documents operation queries for documents where the value of the gender field is female.$elemMatch
projection returns only the first matching element of the child array where the complexion field is fair.|
| Name | Description | Usage |
|:—–|:————|:—–:|
| $elemMatch | Returns a document if an element within the array field matches all of the $elemMatch
conditions. | db.family.find( { gender: “”female”” }, { child: { $elemMatch: { complexion: “”fair”” } } } )
- The operator
$all
returns documents that match all the elements in an array of a specified field.
{ <field>: { $all: [ <value1> , <value2> .. ] } }
The
$size
operator argument must return all documents specified by an array, so it must find the solution to the array. It matches all elements within a range.This example shows the family collection where there are 2 elements in the query operator argument
$size
. Pokemon unity.
db.family.find( { field: { $size: 2 } } );
Logical Query Operators
The
$not
query operator selects documents that are not a particular value that is specified in the query. Use this query operator when you want to find all but a particular value.An example below shows the use of the
$not
query to return certain documents in the family collection. The specified field is the age field and it should be a value of 15 or less than that. If a document doesn’t have an age field, it will also be placed in the search results.
| Name | Description | Usage |
|:—–|:————|:—–:|
Mongodb Query Language Cheat Sheet
| $not | Returns documents that don’t match the query expression.| db.family.find( { age: { $not: { $gt: 15 } } } )
- The
$nor
query operator returns documents that fail all expressions in an array.|{ $nor: [ { <expression1> }, { <expression2> }, .. { <expressionn> } ] }
|
The
$and
query operator adds consecutive query clauses and returns documents that meet all the clauses criteria.This example shows the
$and
operator and two clauses. All of documents will return that meet the entire criteria specified by the two clauses. A document that matches one but not the other clause will not be returned. Here, the seach is for the family collection. The age field has two clauses for documents to match:
(1) not equal to 5 and (2) the age field exists
db.family.find( { $and: [ { age: { $ne: 5 } }, { age: { $exists: true } } ] } )
The
$or
query returns documents that match one or more clauses.The example shown queries the famiy collection. The age field of a document can either have a field value of 7 or less OR the complexion field value of “fair.”
|db.family.find( { $or: [ { age: { $lt: 7 } }, { complexion: 'fair' } ] } )
Evaluation Query Operators
- The
$where
query operator This command will return documents from family collection where first name is equal to Yeshua.|
| Name | Description | Usage |
|:—–|:————|:—–|
Mongodb Injection Cheat Sheet Printable
|$where | Returns documents that match a JavaScript expression. | db.family.find( { $where: function() { return (this.name.first 'Yeshua') }}).pretty()
The
$regex
query operator returns documents the match the stated expression.The example shown here returns documents where the first name has a value of “R.” The family collection is queried.
db.family.find( { ''name.first': { $regex: 'R.*' } } )
The
$expr
grants usage of expressions use of gathering of expressions within the query language.The below example shows
$expr
the operator query to return documents where the number of finished aricles is more than the monthly article quota.
db.articleMonthly.find( { $expr: { $gt: [ '$articleFinished' , '$articleQuota' ] } } )
- The
$text
query operator runs a text search for fields in a text index. The string should look like this:
{
$text:
{
$search: <string>,
$language: <string>,
$caseSensitive: <boolean>,
$diacriticSensitive: <boolean>
}
}
- The
$search
string queries the text index in the MongoDB database.
- The
$language
argument is optional. It determines the searchs stop words list. You can select “None” for stop words and it will return documents that match the conditions of the string query.
- The
$caseSensitive
boolean flag is optional. Use it to disable or enable case sensitivity in a text index search. The default selection is case insensitivity, that is, the default is irrespective of case.
- The
$diacriticSensitive
boolean flag is optional in version 3 text indexes. Use it to disable or enable diacritic marks or signs in a text index search. Earlier versions automatically default to diacritic insensitivity.
The
$mod
(modulo) query operator is used to return documents that match an indicated$mod
expression. The syntax shows the specified remainder of a field’s given value. That value was divided by a number (divisor)The
$mod
has changed starting with the 2.6 version. It passes an error when the remainder is fewer or more than the specified remainder in the array. Earlier versions didn’t pass an error when a remainder is zero.Here’s an example where documents will be returned from the family colllection. The age field
$mod
is 7, the specified remainder is 0.
db.family.find( { age: { $mod: [ 7, 0 ] } } )
Element Query Operators
The
$exists
operator returns documents that match all of the criteria indicated in the value field.The example below shows that in the family collection, documents will be returned REVIEW THIS PART ONLY
will documents in the family collection where the age field exists and its value does not equal 5 or 15.|
| Name | Description | Usage |
|:—–|:————|:—–|
|$exists| Matches documents that contain the indicated values.|db.family.find( { age: { $exists: true, $nin: [ 3, 21 ] } } )
The
$type
operator returns documents that are of a certain BSON type(3). An instance of that type is the field’s value, and this is what documents must match in order to be returned in the search results.The query below is an example of the
$type
operator that returns documents that match the BSON types in the order given by type.
{ field: { $type: [ <bson type1='type1'> , <bson type2='type2'>, .. ] } }
Conclusion
The MongoDB database query operator cheat sheet is an excellent resource for beginners and experts alike. It contains comparison, array, logical, evaluation, element and more commonly used query operators. Refer to it often. Think of the cheat sheet as your helpmate for efficient coding in all of your MongoDB projects.
Mongodb Query Injection Cheat Sheet
NoSQL injection vulnerabilities allow attackers to inject code into commands for databases that don’t use SQL queries, such as MongoDB. NoSQL injection attacks can be especially dangerous because code is injected and executed on the server in the language of the web application, potentially allowing arbitrary code execution. Let’s see how NoSQL injection differs from traditional SQL injection and what you can do to prevent it.
A Quick Introduction to NoSQL
Even if you don’t work with databases, you’ve probably heard of NoSQL among the cloud-related buzzwords of the past few years. NoSQL (a.k.a. “non-SQL” or “not only SQL”) is a general term covering databases that don’t use the SQL query language. In practice, it’s used to refer to non-relational databases that are growing in popularity as the back-end for distributed cloud platforms and web applications. Instead of storing data in tables, as with relational databases, NoSQL data stores use other data models that are better suited for specific purposes, such as documents, graphs, objects, and many others.
MongoDB, currently one of the most popular NoSQL database products, stores data as documents using a syntax similar to JSON (JavaScript Object Notation). Among other benefits, this allows developers to build full-stack applications using only JavaScript. We will use MongoDB queries to demonstrate how attackers can exploit unvalidated user input to inject code into a web application backed by a NoSQL database.
Why MongoDB Injection Is Possible
With traditional SQL injection, the attacker exploits unsafe user input processing to modify or replace SQL queries (or other SQL statements) that the application sends to a database engine. In other words, an SQL injection allows the attacker to execute commands in the database. Unlike relational databases, NoSQL databases don't use a common query language. NoSQL query syntax is product-specific and queries are written in the programming language of the application: PHP, JavaScript, Python, Java, and so on. This means that a successful injection lets the attacker execute commands not only in the database, but also in the application itself, which can be far more dangerous.
MongoDB uses the Binary JSON (BSON) data format and comes with a secure BSON query assembly tool. Queries are also represented as BSON objects (i.e. binary data), so direct string injection is not possible. However, MongoDB deliberately allows applications to run JavaScript on the server within the $where
and mapReduce
operations. The documentation is very clear that if this functionality is used, the developer should take care to prevent users from submitting malicious JavaScript. In other words, MongoDB deliberately includes a potential injection vector. So what can a malicious user do if the developer is not careful?
Simple MongoDB Injection in PHP
For a basic authentication bypass, the attacker can try to enter MongoDB operators in field values, for example $eq
(equals), $ne
(not equal to) or $gt
(greater than). Here’s an unsafe way to build a database query in a PHP application, with the parameter values taken directly from a form:
If this query is then used to check login credentials, the attacker can abuse PHP’s built-in associative array processing to inject a MongoDB query that always returns true and bypass the authentication process. This may be as simple as sending the following POST request:
PHP will translate this into an array of arrays:
When sent as a MongoDB query to a user store, this will find all users where the user name and password are not equal to 1, which is highly likely to be true and may allow the attacker to bypass authentication.
JavaScript Injection in MongoDB
Let’s say we have a vulnerable application where the developer uses MongoDB’s $where
query operator with unvalidated user inputs. This allows an attacker to inject malicious input containing JavaScript code. While the attacker can’t inject completely arbitrary JavaScript, only code that uses a limited set of functions, this is quite enough for a useful attack.
To query a MongoDB data store with the $where
operator, you would normally use the find()
function, for example:
This would match records with name Netsparker. A vulnerable PHP application might directly insert unsanitized user input when building the query, for example from the variable $userData
:
The attacker might then inject an exploit string like 'a'; sleep(5000)
into $userData
to have the server pause for 5 seconds if the injection was successful. The query executed by the server would be:
Because queries are written in the application language, this is just one of the many types of injection possible. For example, if Node.js is used for server-side scripting, as in the popular MEAN stack (MongoDB, ExpressJS, AngularJS, and Node.js), server-side JavaScript injection into Node.js may be possible.
Preventing NoSQL Injection Attacks
Mongodb Injection Attacks
The consequences of a successful MongoDB injection or other NoSQL injection attack can be even more serious than with traditional SQL injection. Attackers can not only extract data from the database, but also execute code in the context of the application, for example to perform denial of service attacks or even compromise admin user accounts and take control of the server. Such attacks are especially dangerous since NoSQL data stores are often a novelty to developers familiar only with relational database products, which increases the risk of insecure code.
Many popular NoSQL products are still young and under intense development, so it’s always a good idea to use the most recent version. For example, earlier versions of MongoDB were notoriously insecure on many levels and had serious injection vulnerabilities, while in more recent versions, security is taken much more seriously.
Mongodb Injection Cheat Sheet Template
As is often the case in web application security, the best way to prevent NoSQL injection attacks is to avoid using unsanitized user inputs in application code, especially when building database queries. MongoDB, for example, has built-in features for secure query building without JavaScript. If you do need to use JavaScript in queries, follow the usual best practices: validate and encode all user inputs, apply the rule of least privilege, and know your language to avoid using vulnerable constructs. For more advice, see the OWASP page on testing for NoSQL injection.