Mongo Shell, Query Operators, Update Operators and a Few Commands
In MongoDB, the CRUD operations are:
- Create:
insert
- Read:
find
- Update:
update
- Delete:
remove
MongoDB's CRUD operations exist as methods/functions in programming language APIs, not as a separate language. You should manipulate documents in the database using objects in your programming language.
Mongo shell is an interactive Javascript interpreter that allows you to connect to MongoDB and manipulate its data. This means you can execute Javascript inside the shell:
> for (i = 0; i < 3; i++) print("Hello!");
Hello!
Hello!
Hello!
It also has tab completions for Javascript and other commands. For example, typing pri
and pressing the Tab key, it will complete the word print
, a common Javascript function.
MongoDB uses BSON to represent data in the database. The specification for BSON is give at bsonspec.org.
> doc = { "name" : "Smith", "age" : 30, "profession" : "hacker" }
{ "name" : "Smith", "age" : 30, "profession" : "hacker" }
> db
test
> db.people.insert(doc)
> db.people.find()
{ "_id" : ObjectId("525db09800fa8276d3d083d4"), "name" : "Smith", "age" : 30, "profession" : "hacker" }
> db.people.insert({ "name" : "Jones", "age" : 35, "profession" : "baker" })
> db.people.find()
{ "_id" : ObjectId("525db09800fa8276d3d083d4"), "name" : "Smith", "age" : 30, "profession" : "hacker" }
{ "_id" : ObjectId("525db17400fa8276d3d083d5"), "name" : "Jones", "age" : 35, "profession" : "baker" }
- db.[collection].insert({...})
- The collection unique ID field is called “_id” and can be provided. If not provided an ObjectID will be
- generated based on the time, machine, process-id and process dependent counter.
- “_id” does not have to be a scalar value – it can be a document, e.g. _id : {a:1, b:’ronald’}
> db.people.findOne()
{
"_id" : ObjectId("525db09800fa8276d3d083d4"),
"name" : "Smith",
"age" : 30,
"profession" : "hacker"
}
> db.people.findOne({ "name" : "Jones" })
{
"_id" : ObjectId("525db17400fa8276d3d083d5"),
"name" : "Jones",
"age" : 35,
"profession" : "baker"
}
> db.people.findOne({ "name" : "Jones" }, { "name" : true, "_id" : false })
{ "name" : "Jones" }
> db.people.findOne({ "name" : "Jones" }, { "name" : true })
{ "_id" : ObjectId("525db17400fa8276d3d083d5"), "name" : "Jones" }
- db.[collection].findOne({...}, {field1 : true, ...}).pretty() //no argument will find all docs
- db.[collection].find({...}, {field1 : true, ...}).pretty() //no argument will find all docs
- db.[collection].count({...})
You can use the find method in different ways. See below:
> db.scores.find( { student: 19 } );
> db.scores.find( { student: 19, type: "essay"} );
// Limit the type returned from the find method
> db.scores.find({ student: 19, type: "essay" }, { score: true, _id: false });
// Retrieve documents that have a score greater than 95.
> db.scores.find({ score : { $gt : 95 } });
// Retrieve documents that have a score greater than
// 40 and less or equal to 70, with the type essay
> db.scores.find({ score : { $gt: 40, $lte : 70 }, type: "essay" });
- ranges: {myField: {$gt: 100, $lt: 10}} $gte, $lte -> Can be applied to numbers and strings (ASCII)
- $not - negates result of other operation or regular expression query
- tags: {$ne: “gardening”} // works on keys pointing to single values or arrays – inefficient – can’t use indexes
- regex: {myField: {$regex: “a$”}}
- {myField: {$exists: true}} //checks if particular key exists in document
- {myField: {$type: 2}} // 2=String as defined in BSON spec
- {$or: [{...}, {...}, ...]}
- {$and: [{...}, {...}, ...]}
- {myArrayField: “test”} -> Will find any documents where the array contains the value “test”
- {myArrayField.0 : “test”} -> Value at particular position within array
- {myArrayField: {$size: 3}} -> array with three elements
- operator: {myField: {$in: [“one”, “two”, ...]}} $nin
- array-operator: {myArrayField: {$all: [“one”, “two”, ...]}} -> array contains all given values in any order
- {“myField.mySubfield” : “test”} // Dot-Notation needs to be put in “”
- {“myArrayField.0.mySubfield” : “test”} // stipulate zeroth element of array
- {“myArrayField.mySubfield” : “test”} // search in any of the array elements
- {myArrayField : {$elemMatch: { mySubfield : “test”, mySubfield2 : “test2”}}} // restrict multiple conditions to same subdocument of array field
- myCursor = db.[collection].find(); null; // append null as not to print out the cursor immediately
- myCursor.hasNext() myCursor.next()
- myCursor.skip(2).limit(5).sort({name : -1}); null; // modifies the query executed on the server
- db.[collection].count({...})
- db.[collection].update({ myQuery }, {myField: “newValue”, ... }) // replaces the existing document
- db.[collection].update({ myQuery }, {$set : {myField: “newValue”}}) //> Create or update myField
- db.[collection].update({ myQuery }, {$inc : {age: 1}}) // increment a value for age
- db.[collection].update({ myQuery }, {$set : {“myArray.2”: “x”}}) // Set 3. position of Array
- db.[collection].update({ myQuery }, {$unset : {myField: 1}})
- db.[collection].update({ myQuery }, {$push : {myArray: “y”}})
- db.[collection].update({ myQuery }, {$pop : {myArray: 1}}) // pop right-most
- db.[collection].update({ myQuery }, {$pop : {myArray: -1}}) // pop left-most
- db.[collection].update({ myQuery }, {$pull : {myArray: “c”}}) // remove value “c”
- db.[collection].update({ myQuery }, {$pushAll : {myArray: [“a”, “b”, “c”]}})
- db.[collection].update({ myQuery }, {$pullAll : {myArray: [“a”, “b”, “c”]}})
- db.[collection].update({ myQuery }, {$addToSet : {myArray: “y”}}) //will only add if does not exist yet
- db.[collection].update({ myQuery }, {$set : {myField: “newValue”}}, {upsert: true}) // Create or update document specified by { myQuery } with myField
- db.[collection].update({}, {$set: {title: “Dr.”}}, {multi: true}) // {} matches all documents
- db.[collection].remove({...}) // no argument will remove all documents from collection – not isolated
- db.[collection].drop() // faster but drops collection including indexes