Mongodb Notes
Mongodb Notes
1. db.books.find ( { price: { $eq: 300 } } )
The above example queries the books collection to select all documents where the value of the price
filed equals 300.
The $gt chooses a document where the value of the field is greater than the specified value.
Syntax:
1. { field: { $gt: value } }
$gte
The $gte choose the documents where the field value is greater than or equal to a specified value.
Syntax:
1. { field: { $gte: value } }
$in
The $in operator choose the documents where the value of a field equals any value in the specified
array.
Syntax:
1. { filed: { $in: [ <value1>, <value2>, ……] } }
Example:
1. db.books.find( { price: { $in: [100, 200] } } )
$lt
The $lt operator chooses the documents where the value of the field is less than the specified value.
Syntax:
1. { field: { $lt: value } }
Example:
1. db.books.find ( { price: { $lt: 20 } } )
$lte
The $lte operator chooses the documents where the field value is less than or equal to a specified
value.
Syntax:
1. { field: { $lte: value } }
Example:
1. db.books.find ( { price: { $lte: 250 } } )
$ne
The $ne operator chooses the documents where the field value is not equal to the specified value.
Syntax:
1. { <field>: { $ne: <value> } }
Example:
1. db.books.find ( { price: { $ne: 500 } } )
$nin
The $nin operator chooses the documents where the field value is not in the specified array or does
not exist.
Syntax:
1. { field : { $nin: [ <value1>, <value2>, .... ] } }
Example:
1. db.books.find ( { price: { $nin: [ 50, 150, 200 ] } } )
LOGICAL OPERATOR
$and
The $and operator works as a logical AND operation on an array. The array should be of one or more
expressions and chooses the documents that satisfy all the expressions in the array.
Syntax:
1. { $and: [ { <exp1> }, { <exp2> }, ....]}
$not
The $not operator works as a logical NOT on the specified expression and chooses the documents
that are not related to the expression.
Syntax:
1. { field: { $not: { <operator-expression> } } }
Example:
1. db.books.find ( { price: { $not: { $gt: 200 } } } )
$nor
The $nor operator works as logical NOR on an array of one or more query expression and chooses
the documents that fail all the query expression in the array.
Syntax:
1. { $nor: [ { <expression1> } , { <expresion2> } , ..... ] }
$or
It works as a logical OR operation on an array of two or more expressions and chooses documents
that meet the expectation at least one of the expressions.
Syntax:
1. { $or: [ { <exp_1> }, { <exp_2> }, ... , { <exp_n> } ] }
Example:
1. db.books.find ( { $or: [ { quantity: { $lt: 200 } }, { price: 500 } ] } )
MongoDB Element Operator
$exists
The exists operator matches the documents that contain the field when Boolean is true. It also
matches the document where the field value is null.
Syntax:
1. { field: { $exists: <boolean> } }
Example:
1. db.books.find ( { qty: { $exists: true, $nin: [ 5, 15 ] } } )
$type
The type operator chooses documents where the value of the field is an instance of the specified
BSON type.
Syntax:
1. { field: { $type: <BSON type> } }
The expr operator allows the use of aggregation expressions within the query language.
Syntax:
1. { $expr: { <expression> } }
Example:
1. db.store.find( { $expr: {$gt: [ "$product" , "price" ] } } )
$jsonSchema
Syntax:
1. { $jsonSchema: <JSON schema object> }
$mod
The mod operator selects the document where the value of a field is divided by a divisor has the
specified remainder.
Syntax:
1. { field: { $mod: [ divisor, remainder ] } }
Example:
1. db.books.find ( { qty: { $mod: [ 200, 0] } } )
$regex
It provides regular expression abilities for pattern matching strings in queries. The MongoDB uses
regular expressions that are compatible with Perl.
Syntax:
1. { <field>: /pattern/<options> }
Example:
1. db.books.find( { price: { $regex: /789$/ } } )
$text
The $text operator searches a text on the content of the field, indexed with a text index.
Syntax:
1. {
2. $text:
3. {
4. $search: <string>,
5. $language: <string>,
6. $caseSensitive: <boolean>,
7. $diacriticSensitive: <boolean>
8. }
9. }
Example:
1. db.books.find( { $text: { $search: "Othelo" } } )
$where
The "where" operator is used for passing either a string containing a JavaScript expression or a full
JavaScript function to the query system.
Example:
1. db.books.find( { $where: function() {
2. return (hex_md5(this.name)== "9b53e667f30cd329dca1ec9e6a8")
3. } } );
In MongoDB, limit() method is used to limit the fields of document that you want to show.
Sometimes, you have a lot of fields in collection of your database and have to retrieve only 1 or 2. In
such case, limit() method is used.
Syntax:
1. db.COLLECTION_NAME.find().limit(NUMBER)
Scenario:
1. [
2. {
3. Course: "Java",
4. details: { Duration: "6 months", Trainer: "Sonoo Jaiswal" },
5. Batch: [ { size: "Medium", qty: 25 } ],
6. category: "Programming Language"
7. },
8. {
9. Course: ".Net",
10. details: { Duration: "6 months", Trainer: "Prashant Verma" },
11. Batch: [ { size: "Small", qty: 5 }, { size: "Medium", qty: 10 }, ],
12. category: "Programming Language"
13. },
14. {
15. Course: "Web Designing",
16. details: { Duration: "3 months", Trainer: "Rashmi Desai" },
17. Batch: [ { size: "Small", qty: 5 }, { size: "Large", qty: 10 } ],
18. category: "Programming Language"
19. }
20. ];
Example
1. db.javatpoint.find().limit(1)
Output:
In MongoDB, skip() method is used to skip the document. It is used with find() and limit() methods.
Syntax
1. db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)
Scenario:
Consider here also the above discussed example. The collection javatpoint has three documents.
1. [
2. {
3. Course: "Java",
4. details: { Duration: "6 months", Trainer: "Sonoo Jaiswal" },
5. Batch: [ { size: "Medium", qty: 25 } ],
6. category: "Programming Language"
7. },
8. {
9. Course: ".Net",
10. details: { Duration: "6 months", Trainer: "Prashant Verma" },
11. Batch: [ { size: "Small", qty: 5 }, { size: "Medium", qty: 10 }, ],
12. category: "Programming Language"
13. },
14. {
15. Course: "Web Designing",
16. details: { Duration: "3 months", Trainer: "Rashmi Desai" },
17. Batch: [ { size: "Small", qty: 5 }, { size: "Large", qty: 10 } ],
18. category: "Programming Language"
19. }
20. ];
Execute the following query to retrieve only one document and skip 2 documents.
Example
1. db.javatpoint.find().limit(1).skip(2)
Output:
Programming Language" }
As you can see, the skip() method has skipped first and second documents and shows only third
document.
MongoDB sort() method
In MongoDB, sort() method is used to sort the documents in the collection. This method accepts a
document containing list of fields along with their sorting order.
Syntax:
1. db.COLLECTION_NAME.find().sort({KEY:1})
Scenario
1. [
2. {
3. Course: "Java",
4. details: { Duration: "6 months", Trainer: "Sonoo Jaiswal" },
5. Batch: [ { size: "Medium", qty: 25 } ],
6. category: "Programming Language"
7. },
8. {
9. Course: ".Net",
10. details: { Duration: "6 months", Trainer: "Prashant Verma" },
11. Batch: [ { size: "Small", qty: 5 }, { size: "Medium", qty: 10 }, ],
12. category: "Programming Language"
13. },
14. {
15. Course: "Web Designing",
16. details: { Duration: "3 months", Trainer: "Rashmi Desai" },
17. Batch: [ { size: "Small", qty: 5 }, { size: "Large", qty: 10 } ],
18. category: "Programming Language"
19. }
Execute the following query to display the documents in descending order.
1. db.javatpoint.find().sort({"Course":-1})
Note: By default sort() method displays the documents in ascending order. If you don't specify the
sorting preference, it will display documents in ascending order.
Indexes support the efficient resolution of queries. Without indexes, MongoDB must scan every
document of a collection to select those documents that match the query statement. This scan is
highly inefficient and require MongoDB to process a large volume of data.
Indexes are special data structures, that store a small portion of the data set in an easy-to-traverse
form. The index stores the value of a specific field or set of fields, ordered by the value of the field as
specified in the index.
Syntax
>db.COLLECTION_NAME.createIndex({KEY:1})
Here key is the name of the field on which you want to create index and 1 is for ascending order. To
create index in descending order you need to use -1.
Example
>db.mycol.createIndex({"title":1})
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
>
In createIndex() method you can pass multiple fields, to create index on multiple fields.
>db.mycol.createIndex({"title":1,"description":-1})
>
You can drop a particular index using the dropIndex() method of MongoDB.
Syntax
>db.COLLECTION_NAME.dropIndex({KEY:1})
Here key is the name of the file on which you want to create index and 1 is for ascending order. To
create index in descending order you need to use -1.
Example
> db.mycol.dropIndex({"title":1})
"ok" : 0,
"code" : 27,
"codeName" : "IndexNotFound"
Syntax
>db.COLLECTION_NAME.dropIndexes()
Example
Assume we have created 2 indexes in the named mycol collection as shown below −
> db.mycol.createIndex({"title":1,"description":-1})
>db.mycol.dropIndexes({"title":1,"description":-1})
{ "nIndexesWas" : 2, "ok" : 1 }
>
This method returns the description of all the indexes int the collection.
Syntax
db.COLLECTION_NAME.getIndexes()
Example
Assume we have created 2 indexes in the named mycol collection as shown below −
> db.mycol.createIndex({"title":1,"description":-1})
> db.mycol.getIndexes()
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "test.mycol"
},
"v" : 2,
"key" : {
"title" : 1,
"description" : -1
},
},
"name" : "title_1_description_-1",
"ns" : "test.mycol"