Statistics
71
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2025-11-22

AuthorGoalKicker.com

This MongoDB® Notes for Professionals book is compiled from Stack Overflow Documentation , the content is written by the beautiful people at Stack Overflow. Text content is released under Creative Commons BY-SA.

Tags
No tags
Publisher: GoalKicker.com
Publish Year: 2017
Language: 英文
Pages: 72
File Format: PDF
File Size: 931.0 KB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

MongoDB Notes for ProfessionalsMongoDB® Notes for Professionals GoalKicker.com Free Programming Books Disclaimer This is an unocial free book created for educational purposes and is not aliated with ocial MongoDB® group(s) or company(s). All trademarks and registered trademarks are the property of their respective owners 60+ pages of professional hints and tricks
Contents About 1 ................................................................................................................................................................................... Chapter 1: Getting started with MongoDB 2 ....................................................................................................... Section 1.1: Execution of a JavaScript file in MongoDB 2 ............................................................................................. Section 1.2: Making the output of find readable in shell 2 ............................................................................................ Section 1.3: Complementary Terms 3 ............................................................................................................................. Section 1.4: Installation 3 .................................................................................................................................................. Section 1.5: Basic commands on mongo shell 6 ............................................................................................................ Section 1.6: Hello World 6 ................................................................................................................................................. Chapter 2: CRUD Operation 7 ..................................................................................................................................... Section 2.1: Create 7 ......................................................................................................................................................... Section 2.2: Update 7 ....................................................................................................................................................... Section 2.3: Delete 8 ......................................................................................................................................................... Section 2.4: Read 8 ........................................................................................................................................................... Section 2.5: Update of embedded documents 9 .......................................................................................................... Section 2.6: More update operators 10 .......................................................................................................................... Section 2.7: "multi" Parameter while updating multiple documents 10 ...................................................................... Chapter 3: Getting database information 11 ..................................................................................................... Section 3.1: List all collections in database 11 ............................................................................................................... Section 3.2: List all databases 11 .................................................................................................................................... Chapter 4: Querying for Data (Getting Started) 12 ....................................................................................... Section 4.1: Find() 12 ......................................................................................................................................................... Section 4.2: FindOne() 12 ................................................................................................................................................. Section 4.3: limit, skip, sort and count the results of the find() method 12 ................................................................ Section 4.4: Query Document - Using AND, OR and IN Conditions 14 ....................................................................... Section 4.5: find() method with Projection 16 ................................................................................................................ Section 4.6: Find() method with Projection 16 ............................................................................................................... Chapter 5: Update Operators 18 .............................................................................................................................. Section 5.1: $set operator to update specified field(s) in document(s) 18 ................................................................. Chapter 6: Upserts and Inserts 20 ............................................................................................................................ Section 6.1: Insert a document 20 ................................................................................................................................... Chapter 7: Collections 21 .............................................................................................................................................. Section 7.1: Create a Collection 21 .................................................................................................................................. Section 7.2: Drop Collection 22 ....................................................................................................................................... Chapter 8: Aggregation 23 ........................................................................................................................................... Section 8.1: Count 23 ........................................................................................................................................................ Section 8.2: Sum 23 .......................................................................................................................................................... Section 8.3: Average 24 ................................................................................................................................................... Section 8.4: Operations with arrays 25 .......................................................................................................................... Section 8.5: Aggregate query examples useful for work and learning 25 ................................................................. Section 8.6: Match 29 ....................................................................................................................................................... Section 8.7: Get sample data 30 ..................................................................................................................................... Section 8.8: Remove docs that have a duplicate field in a collection (dedupe) 30 .................................................. Section 8.9: Left Outer Join with aggregation ( $Lookup) 30 ..................................................................................... Section 8.10: Server Aggregation 31 .............................................................................................................................. Section 8.11: Aggregation in a Server Method 31 .......................................................................................................... Section 8.12: Java and Spring example 32 ....................................................................................................................
Chapter 9: Indexes 34 ...................................................................................................................................................... Section 9.1: Index Creation Basics 34 .............................................................................................................................. Section 9.2: Dropping/Deleting an Index 36 .................................................................................................................. Section 9.3: Sparse indexes and Partial indexes 36 ...................................................................................................... Section 9.4: Get Indices of a Collection 37 ..................................................................................................................... Section 9.5: Compound 38 ............................................................................................................................................... Section 9.6: Unique Index 38 ........................................................................................................................................... Section 9.7: Single field 38 ............................................................................................................................................... Section 9.8: Delete 38 ....................................................................................................................................................... Section 9.9: List 39 ............................................................................................................................................................ Chapter 10: Bulk Operations 40 ................................................................................................................................. Section 10.1: Converting a field to another type and updating the entire collection in Bulk 40 ............................... Chapter 11: 2dsphere Index 43 .................................................................................................................................... Section 11.1: Create a 2dsphere Index 43 ........................................................................................................................ Chapter 12: Pluggable Storage Engines 44 .......................................................................................................... Section 12.1: WiredTiger 44 .............................................................................................................................................. Section 12.2: MMAP 44 ...................................................................................................................................................... Section 12.3: In-memory 44 ............................................................................................................................................. Section 12.4: mongo-rocks 44 ......................................................................................................................................... Section 12.5: Fusion-io 44 ................................................................................................................................................. Section 12.6: TokuMX 45 ................................................................................................................................................... Chapter 13: Java Driver 46 ........................................................................................................................................... Section 13.1: Fetch Collection data with condition 46 .................................................................................................... Section 13.2: Create a database user 46 ........................................................................................................................ Section 13.3: Create a tailable cursor 46 ........................................................................................................................ Chapter 14: Python Driver 48 ...................................................................................................................................... Section 14.1: Connect to MongoDB using pymongo 48 ................................................................................................ Section 14.2: PyMongo queries 48 .................................................................................................................................. Section 14.3: Update all documents in a collection using PyMongo 49 ...................................................................... Chapter 15: Mongo as Shards 50 ............................................................................................................................... Section 15.1: Sharding Environment Setup 50 ................................................................................................................ Chapter 16: Replication 51 ............................................................................................................................................ Section 16.1: Basic configuration with three nodes 51 .................................................................................................. Chapter 17: Mongo as a Replica Set 53 ................................................................................................................. Section 17.1: Mongodb as a Replica Set 53 .................................................................................................................... Section 17.2: Check MongoDB Replica Set states 54 .................................................................................................... Chapter 18: MongoDB - Configure a ReplicaSet to support TLS/SSL 56 ............................................. Section 18.1: How to configure a ReplicaSet to support TLS/SSL? 56 ......................................................................... Section 18.2: How to connect your Client (Mongo Shell) to a ReplicaSet? 58 ............................................................ Chapter 19: Authentication Mechanisms in MongoDB 60 .............................................................................. Section 19.1: Authentication Mechanisms 60 .................................................................................................................. Chapter 20: MongoDB Authorization Model 61 ................................................................................................. Section 20.1: Build-in Roles 61 ......................................................................................................................................... Chapter 21: Configuration 62 ...................................................................................................................................... Section 21.1: Starting mongo with a specific config file 63 ........................................................................................... Chapter 22: Backing up and Restoring Data 64 ................................................................................................ Section 22.1: Basic mongodump of local default mongod instance 64 ...................................................................... Section 22.2: Basic mongorestore of local default mongod dump 64 .......................................................................
Section 22.3: mongoimport with JSON 64 ..................................................................................................................... Section 22.4: mongoimport with CSV 65 ........................................................................................................................ Chapter 23: Upgrading MongoDB version 66 ..................................................................................................... Section 23.1: Upgrading to 3.4 on Ubuntu 16.04 using apt 66 ...................................................................................... Credits 67 .............................................................................................................................................................................. You may also like 69 ........................................................................................................................................................
GoalKicker.com – MongoDB® Notes for Professionals 1 About Please feel free to share this PDF with anyone for free, latest version of this book can be downloaded from: https://goalkicker.com/MongoDBBook This MongoDB® Notes for Professionals book is compiled from Stack Overflow Documentation, the content is written by the beautiful people at Stack Overflow. Text content is released under Creative Commons BY-SA, see credits at the end of this book whom contributed to the various chapters. Images may be copyright of their respective owners unless otherwise specified This is an unofficial free book created for educational purposes and is not affiliated with official MongoDB® group(s) or company(s) nor Stack Overflow. All trademarks and registered trademarks are the property of their respective company owners The information presented in this book is not guaranteed to be correct nor accurate, use at your own risk Please send feedback and corrections to web@petercv.com
GoalKicker.com – MongoDB® Notes for Professionals 2 Chapter 1: Getting started with MongoDB Version Release Date 3.6.1 2017-12-26 3.4 2016-11-29 3.2 2015-12-08 3.0 2015-03-03 2.6 2014-04-08 2.4 2013-03-19 2.2 2012-08-29 2.0 2011-09-12 1.8 2011-03-16 1.6 2010-08-31 1.4 2010-03-25 1.2 2009-12-10 Section 1.1: Execution of a JavaScript file in MongoDB ./mongo localhost:27017/mydb myjsfile.js Explanation: This operation executes the myjsfile.js script in a mongo shell that connects to the mydb database on the mongod instance accessible via the localhost interface on port 27017. localhost:27017 is not mandatory as this is the default port mongodb uses. Also, you can run a .js file from within mongo console. >load("myjsfile.js") Section 1.2: Making the output of find readable in shell We add three records to our collection test as: > db.test.insert({"key":"value1","key2":"Val2","key3":"val3"}) WriteResult({ "nInserted" : 1 }) > db.test.insert({"key":"value2","key2":"Val21","key3":"val31"}) WriteResult({ "nInserted" : 1 }) > db.test.insert({"key":"value3","key2":"Val22","key3":"val33"}) WriteResult({ "nInserted" : 1 }) If we see them via find, they will look very ugly. > db.test.find() { "_id" : ObjectId("5790c5cecae25b3d38c3c7ae"), "key" : "value1", "key2" : "Val2 ", "key3" : "val3" } { "_id" : ObjectId("5790c5d9cae25b3d38c3c7af"), "key" : "value2", "key2" : "Val2 1", "key3" : "val31" } { "_id" : ObjectId("5790c5e9cae25b3d38c3c7b0"), "key" : "value3", "key2" : "Val2 2", "key3" : "val33" } To work around this and make them readable, use the pretty() function. > db.test.find().pretty()
GoalKicker.com – MongoDB® Notes for Professionals 3 { "_id" : ObjectId("5790c5cecae25b3d38c3c7ae"), "key" : "value1", "key2" : "Val2", "key3" : "val3" } { "_id" : ObjectId("5790c5d9cae25b3d38c3c7af"), "key" : "value2", "key2" : "Val21", "key3" : "val31" } { "_id" : ObjectId("5790c5e9cae25b3d38c3c7b0"), "key" : "value3", "key2" : "Val22", "key3" : "val33" } > Section 1.3: Complementary Terms SQL Terms MongoDB Terms Database Database Table Collection Entity / Row Document Column Key / Field Table Join Embedded Documents Primary Key Primary Key (Default key _id provided by mongodb itself) Section 1.4: Installation To install MongoDB, follow the steps below: For Mac OS: There are two options for Mac OS: manual install or homebrew. Installing with homebrew: Type the following command into the terminal: $ brew install mongodb Installing manually: Download the latest release here. Make sure that you are downloading the appropriate file, specially check whether your operating system type is 32-bit or 64-bit. The downloaded file is in format tgz. Go to the directory where this file is downloaded. Then type the following command: $ tar xvf mongodb-osx-xyz.tgz Instead of xyz, there would be some version and system type information. The extracted folder would be same name as the tgz file. Inside the folder, their would be a subfolder named bin which would contain several binary file along with mongod and mongo. By default server keeps data in folder /data/db. So, we have to create that directory and then
GoalKicker.com – MongoDB® Notes for Professionals 4 run the server having the following commands: $ sudo bash # mkdir -p /data/db # chmod 777 /data # chmod 777 /data/db # exit To start the server, the following command should be given from the current location: $ ./mongod It would start the server on port 27017 by default. To start the client, a new terminal should be opened having the same directory as before. Then the following command would start the client and connect to the server. $ ./mongo By default it connects to the test database. If you see the line like connecting to: test. Then you have successfully installed MongoDB. Congrats! Now, you can test Hello World to be more confident. For Windows: Download the latest release here. Make sure that you are downloading the appropriate file, specially check whether your operating system type is 32-bit or 64-bit. The downloaded binary file has extension exe. Run it. It will prompt an installation wizard. Click Next. Accept the licence agreement and click Next. Select Complete Installation. Click on Install. It might prompt a window for asking administrator's permission. Click Yes. After installation click on Finish. Now, the mongodb is installed on the path C:/Program Files/MongoDB/Server/3.2/bin. Instead of version 3.2, there could be some other version for your case. The path name would be changed accordingly. bin directory contain several binary file along with mongod and mongo. To run it from other folder, you could add the path in system path. To do it: Right click on My Computer and select Properties. Click on Advanced system setting on the left pane. Click on Environment Variables... under the Advanced tab. Select Path from System variables section and click on Edit.... Before Windows 10, append a semi-colon and paste the path given above. From Windows 10, there is a New button to add new path. Click OKs to save changes. Now, create a folder named data having a sub-folder named db where you want to run the server. Start command prompt from their. Either changing the path in cmd or clicking on Open command window here which would be visible after right clicking on the empty space of the folder GUI pressing
GoalKicker.com – MongoDB® Notes for Professionals 5 the Shift and Ctrl key together. Write the command to start the server: > mongod It would start the server on port 27017 by default. Open another command prompt and type the following to start client: > mongo By default it connects to the test database. If you see the line like connecting to: test. Then you have successfully installed MongoDB. Congrats! Now, you can test Hello World to be more confident. For Linux: Almost same as Mac OS except some equivalent command is needed. For Debian-based distros (using apt-get): Import MongoDB Repository key. $ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927 gpg: Total number processed: 1\ gpg: imported: 1 (RSA: 1) Add repository to package list on Ubuntu 16.04. $ echo "deb http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.2.list on Ubuntu 14.04. $ echo "deb http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.2.list Update package list. $ sudo apt-get update Install MongoDB. $ sudo apt-get install mongodb-org For Red Hat based distros (using yum): use a text editor which you prefer. $ vi /etc/yum.repos.d/mongodb-org-3.4.repo Paste following text. [mongodb-org-3.4] name=MongoDB Repository baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.4/x86_64/ gpgcheck=1 enabled=1 gpgkey=https://www.mongodb.org/static/pgp/server-3.4.asc Update package list. $ sudo yum update Install MongoDB $ sudo yum install mongodb-org
GoalKicker.com – MongoDB® Notes for Professionals 6 Section 1.5: Basic commands on mongo shell Show all available databases: show dbs; Select a particular database to access, e.g. mydb. This will create mydb if it does not already exist: use mydb; Show all collections in the database (be sure to select one first, see above): show collections; Show all functions that can be used with the database: db.mydb.help(); To check your currently selected database, use the command db > db mydb db.dropDatabase() command is used to drop a existing database. db.dropDatabase() Section 1.6: Hello World After installation process, the following lines should be entered in mongo shell (client terminal). > db.world.insert({ "speech" : "Hello World!" }); > cur = db.world.find();x=cur.next();print(x["speech"]); Hello World! Explanation: In the first line, we have inserted a { key : value } paired document in the default database test and in the collection named world. In the second line we retrieve the data we have just inserted. The retrieved data is kept in a javascript variable named cur. Then by the next() function, we retrieved the first and only document and kept it in another js variable named x. Then printed the value of the document providing the key.
GoalKicker.com – MongoDB® Notes for Professionals 7 Chapter 2: CRUD Operation Section 2.1: Create db.people.insert({name: 'Tom', age: 28}); Or db.people.save({name: 'Tom', age: 28}); The difference with save is that if the passed document contains an _id field, if a document already exists with that _id it will be updated instead of being added as new. Two new methods to insert documents into a collection, in MongoDB 3.2.x: Use insertOne to insert only one record: db.people.insertOne({name: 'Tom', age: 28}); Use insertMany to insert multiple records: db.people.insertMany([{name: 'Tom', age: 28},{name: 'John', age: 25}, {name: 'Kathy', age: 23}]) Note that insert is highlighted as deprecated in every official language driver since version 3.0. The full distinction being that the shell methods actually lagged behind the other drivers in implementing the method. The same thing applies for all other CRUD methods Section 2.2: Update Update the entire object: db.people.update({name: 'Tom'}, {age: 29, name: 'Tom'}) // New in MongoDB 3.2 db.people.updateOne({name: 'Tom'},{age: 29, name: 'Tom'}) //Will replace only first matching document. db.people.updateMany({name: 'Tom'},{age: 29, name: 'Tom'}) //Will replace all matching documents. Or just update a single field of a document. In this case age: db.people.update({name: 'Tom'}, {$set: {age: 29}}) You can also update multiple documents simultaneously by adding a third parameter. This query will update all documents where the name equals Tom: db.people.update({name: 'Tom'}, {$set: {age: 29}}, {multi: true}) // New in MongoDB 3.2 db.people.updateOne({name: 'Tom'},{$set:{age: 30}) //Will update only first matching document. db.people.updateMany({name: 'Tom'},{$set:{age: 30}}) //Will update all matching documents. If a new field is coming for update, that field will be added to the document.
GoalKicker.com – MongoDB® Notes for Professionals 8 db.people.updateMany({name: 'Tom'},{$set:{age: 30, salary:50000}})// Document will have `salary` field as well. If a document is needed to be replaced, db.collection.replaceOne({name:'Tom'}, {name:'Lakmal',age:25,address:'Sri Lanka'}) can be used. Note: Fields you use to identify the object will be saved in the updated document. Field that are not defined in the update section will be removed from the document. Section 2.3: Delete Deletes all documents matching the query parameter: // New in MongoDB 3.2 db.people.deleteMany({name: 'Tom'}) // All versions db.people.remove({name: 'Tom'}) Or just one // New in MongoDB 3.2 db.people.deleteOne({name: 'Tom'}) // All versions db.people.remove({name: 'Tom'}, true) MongoDB's remove() method. If you execute this command without any argument or without empty argument it will remove all documents from the collection. db.people.remove(); or db.people.remove({}); Section 2.4: Read Query for all the docs in the people collection that have a name field with a value of 'Tom': db.people.find({name: 'Tom'}) Or just the first one: db.people.findOne({name: 'Tom'}) You can also specify which fields to return by passing a field selection parameter. The following will exclude the _id field and only include the age field: db.people.find({name: 'Tom'}, {_id: 0, age: 1})
GoalKicker.com – MongoDB® Notes for Professionals 9 Note: by default, the _id field will be returned, even if you don't ask for it. If you would like not to get the _id back, you can just follow the previous example and ask for the _id to be excluded by specifying _id: 0 (or _id: false).If you want to find sub record like address object contains country, city, etc. db.people.find({'address.country': 'US'}) & specify field too if required db.people.find({'address.country': 'US'}, {'name': true, 'address.city': true})Remember that the result has a `.pretty()` method that pretty-prints resulting JSON: db.people.find().pretty() Section 2.5: Update of embedded documents For the following schema: {name: 'Tom', age: 28, marks: [50, 60, 70]} Update Tom's marks to 55 where marks are 50 (Use the positional operator $): db.people.update({name: "Tom", marks: 50}, {"$set": {"marks.$": 55}}) For the following schema: {name: 'Tom', age: 28, marks: [{subject: "English", marks: 90},{subject: "Maths", marks: 100}, {subject: "Computes", marks: 20}]} Update Tom's English marks to 85 : db.people.update({name: "Tom", "marks.subject": "English"},{"$set":{"marks.$.marks": 85}}) Explaining above example: By using {name: "Tom", "marks.subject": "English"} you will get the position of the object in the marks array, where subject is English. In "marks.$.marks", $ is used to update in that position of the marks array Update Values in an Array The positional $ operator identifies an element in an array to update without explicitly specifying the position of the element in the array. Consider a collection students with the following documents: { "_id" : 1, "grades" : [ 80, 85, 90 ] } { "_id" : 2, "grades" : [ 88, 90, 92 ] } { "_id" : 3, "grades" : [ 85, 100, 90 ] } To update 80 to 82 in the grades array in the first document, use the positional $ operator if you do not know the position of the element in the array: db.students.update( { _id: 1, grades: 80 }, { $set: { "grades.$" : 82 } }
GoalKicker.com – MongoDB® Notes for Professionals 10 ) Section 2.6: More update operators You can use other operators besides $set when updating a document. The $push operator allows you to push a value into an array, in this case we will add a new nickname to the nicknames array. db.people.update({name: 'Tom'}, {$push: {nicknames: 'Tommy'}}) // This adds the string 'Tommy' into the nicknames array in Tom's document. The $pull operator is the opposite of $push, you can pull specific items from arrays. db.people.update({name: 'Tom'}, {$pull: {nicknames: 'Tommy'}}) // This removes the string 'Tommy' from the nicknames array in Tom's document. The $pop operator allows you to remove the first or the last value from an array. Let's say Tom's document has a property called siblings that has the value ['Marie', 'Bob', 'Kevin', 'Alex']. db.people.update({name: 'Tom'}, {$pop: {siblings: -1}}) // This will remove the first value from the siblings array, which is 'Marie' in this case. db.people.update({name: 'Tom'}, {$pop: {siblings: 1}}) // This will remove the last value from the siblings array, which is 'Alex' in this case. Section 2.7: "multi" Parameter while updating multiple documents To update multiple documents in a collection, set the multi option to true. db.collection.update( query, update, { upsert: boolean, multi: boolean, writeConcern: document } ) multi is optional. If set to true, updates multiple documents that meet the query criteria. If set to false, updates one document. The default value is false. db.mycol.find() { "_id" : ObjectId(598354878df45ec5), "title":"MongoDB Overview"} { "_id" : ObjectId(59835487adf45ec6), "title":"NoSQL Overview"} { "_id" : ObjectId(59835487adf45ec7), "title":"Tutorials Point Overview"} db.mycol.update({'title':'MongoDB Overview'}, {$set:{'title':'New MongoDB Tutorial'}},{multi:true})
GoalKicker.com – MongoDB® Notes for Professionals 11 Chapter 3: Getting database information Section 3.1: List all collections in database show collections or show tables or db.getCollectionNames() Section 3.2: List all databases show dbs or db.adminCommand('listDatabases') or db.getMongo().getDBNames()
GoalKicker.com – MongoDB® Notes for Professionals 12 Chapter 4: Querying for Data (Getting Started) Basic querying examples Section 4.1: Find() retrieve all documents in a collection db.collection.find({}); retrieve documents in a collection using a condition ( similar to WHERE in MYSQL ) db.collection.find({key: value}); example db.users.find({email:"sample@email.com"}); retrieve documents in a collection using Boolean conditions (Query Operators) //AND db.collection.find( { $and: [ { key: value }, { key: value } ] }) //OR db.collection.find( { $or: [ { key: value }, { key: value } ] }) //NOT db.inventory.find( { key: { $not: value } } ) more boolean operations and examples can be found here NOTE: find() will keep on searching the collection even if a document match has been found , therefore it is inefficient when used in a large collection , however by carefully modeling your data and/or using indexes you can increase the efficiency of find() Section 4.2: FindOne() db.collection.findOne({}); the querying functionality is similar to find() but this will end execution the moment it finds one document matching its condition , if used with and empty object , it will fetch the first document and return it . findOne() mongodb api documentation Section 4.3: limit, skip, sort and count the results of the find() method Similar to aggregation methods also by the find() method you have the possibility to limit, skip, sort and count the results. Let say we have following collection:
GoalKicker.com – MongoDB® Notes for Professionals 13 db.test.insertMany([ {name:"Any", age:"21", status:"busy"}, {name:"Tony", age:"25", status:"busy"}, {name:"Bobby", age:"28", status:"online"}, {name:"Sonny", age:"28", status:"away"}, {name:"Cher", age:"20", status:"online"} ]) To list the collection: db.test.find({}) Will return: { "_id" : ObjectId("592516d7fbd5b591f53237b0"), "name" : "Any", "age" : "21", "status" : "busy" } { "_id" : ObjectId("592516d7fbd5b591f53237b1"), "name" : "Tony", "age" : "25", "status" : "busy" } { "_id" : ObjectId("592516d7fbd5b591f53237b2"), "name" : "Bobby", "age" : "28", "status" : "online" } { "_id" : ObjectId("592516d7fbd5b591f53237b3"), "name" : "Sonny", "age" : "28", "status" : "away" } { "_id" : ObjectId("592516d7fbd5b591f53237b4"), "name" : "Cher", "age" : "20", "status" : "online" } To skip first 3 documents: db.test.find({}).skip(3) Will return: { "_id" : ObjectId("592516d7fbd5b591f53237b3"), "name" : "Sonny", "age" : "28", "status" : "away" } { "_id" : ObjectId("592516d7fbd5b591f53237b4"), "name" : "Cher", "age" : "20", "status" : "online" } To sort descending by the field name: db.test.find({}).sort({ "name" : -1}) Will return: { "_id" : ObjectId("592516d7fbd5b591f53237b1"), "name" : "Tony", "age" : "25", "status" : "busy" } { "_id" : ObjectId("592516d7fbd5b591f53237b3"), "name" : "Sonny", "age" : "28", "status" : "away" } { "_id" : ObjectId("592516d7fbd5b591f53237b4"), "name" : "Cher", "age" : "20", "status" : "online" } { "_id" : ObjectId("592516d7fbd5b591f53237b2"), "name" : "Bobby", "age" : "28", "status" : "online" } { "_id" : ObjectId("592516d7fbd5b591f53237b0"), "name" : "Any", "age" : "21", "status" : "busy" } If you want to sort ascending just replace -1 with 1 To count the results: db.test.find({}).count() Will return: 5
GoalKicker.com – MongoDB® Notes for Professionals 14 Also combinations of this methods are allowed. For example get 2 documents from descending sorted collection skipping the first 1: db.test.find({}).sort({ "name" : -1}).skip(1).limit(2) Will return: { "_id" : ObjectId("592516d7fbd5b591f53237b3"), "name" : "Sonny", "age" : "28", "status" : "away" } { "_id" : ObjectId("592516d7fbd5b591f53237b4"), "name" : "Cher", "age" : "20", "status" : "online" } Section 4.4: Query Document - Using AND, OR and IN Conditions All documents from students collection. > db.students.find().pretty(); { "_id" : ObjectId("58f29a694117d1b7af126dca"), "studentNo" : 1, "firstName" : "Prosen", "lastName" : "Ghosh", "age" : 25 } { "_id" : ObjectId("58f29a694117d1b7af126dcb"), "studentNo" : 2, "firstName" : "Rajib", "lastName" : "Ghosh", "age" : 25 } { "_id" : ObjectId("58f29a694117d1b7af126dcc"), "studentNo" : 3, "firstName" : "Rizve", "lastName" : "Amin", "age" : 23 } { "_id" : ObjectId("58f29a694117d1b7af126dcd"), "studentNo" : 4, "firstName" : "Jabed", "lastName" : "Bangali", "age" : 25 } { "_id" : ObjectId("58f29a694117d1b7af126dce"), "studentNo" : 5, "firstName" : "Gm", "lastName" : "Anik", "age" : 23 } Similar mySql Query of the above command. SELECT * FROM students;
GoalKicker.com – MongoDB® Notes for Professionals 15 db.students.find({firstName:"Prosen"}); { "_id" : ObjectId("58f2547804951ad51ad206f5"), "studentNo" : "1", "firstName" : "Prosen", "lastName" : "Ghosh", "age" : "23" } Similar mySql Query of the above command. SELECT * FROM students WHERE firstName = "Prosen"; AND Queries db.students.find({ "firstName": "Prosen", "age": { "$gte": 23 } }); { "_id" : ObjectId("58f29a694117d1b7af126dca"), "studentNo" : 1, "firstName" : "Prosen", "lastName" : "Ghosh", "age" : 25 } Similar mySql Query of the above command. SELECT * FROM students WHERE firstName = "Prosen" AND age >= 23 Or Queries db.students.find({ "$or": [{ "firstName": "Prosen" }, { "age": { "$gte": 23 } }] }); { "_id" : ObjectId("58f29a694117d1b7af126dca"), "studentNo" : 1, "firstName" : "Prosen", "lastName" : "Ghosh", "age" : 25 } { "_id" : ObjectId("58f29a694117d1b7af126dcb"), "studentNo" : 2, "firstName" : "Rajib", "lastName" : "Ghosh", "age" : 25 } { "_id" : ObjectId("58f29a694117d1b7af126dcc"), "studentNo" : 3, "firstName" : "Rizve", "lastName" : "Amin", "age" : 23 } { "_id" : ObjectId("58f29a694117d1b7af126dcd"), "studentNo" : 4, "firstName" : "Jabed", "lastName" : "Bangali", "age" : 25 } { "_id" : ObjectId("58f29a694117d1b7af126dce"), "studentNo" : 5, "firstName" : "Gm", "lastName" : "Anik", "age" : 23 } Similar mySql Query of the above command. SELECT * FROM students WHERE firstName = "Prosen" OR age >= 23 And OR Queries db.students.find({
GoalKicker.com – MongoDB® Notes for Professionals 16 firstName : "Prosen", $or : [ {age : 23}, {age : 25} ] }); { "_id" : ObjectId("58f29a694117d1b7af126dca"), "studentNo" : 1, "firstName" : "Prosen", "lastName" : "Ghosh", "age" : 25 } Similar mySql Query of the above command. SELECT * FROM students WHERE firstName = "Prosen" AND age = 23 OR age = 25; IN Queries This queries can improve multiple use of OR Queries db.students.find(lastName:{$in:["Ghosh", "Amin"]}) { "_id" : ObjectId("58f29a694117d1b7af126dca"), "studentNo" : 1, "firstName" : "Prosen", "lastName" : "Ghosh", "age" : 25 } { "_id" : ObjectId("58f29a694117d1b7af126dcb"), "studentNo" : 2, "firstName" : "Rajib", "lastName" : "Ghosh", "age" : 25 } { "_id" : ObjectId("58f29a694117d1b7af126dcc"), "studentNo" : 3, "firstName" : "Rizve", "lastName" : "Amin", "age" : 23 } Similar mySql query to above command SELECT * FROM students WHERE lastName IN ('Ghosh', 'Amin') Section 4.5: find() method with Projection The basic syntax of find() method with projection is as follows > db.COLLECTION_NAME.find({},{KEY:1}); If you want to show all documents without the age field then the command is as follows db.people.find({},{age : 0}); If you want to show all documents the age field then the command is as follows Section 4.6: Find() method with Projection In MongoDB, projection means selecting only the necessary data rather than selecting whole of the data of a document. The basic syntax of find() method with projection is as follows > db.COLLECTION_NAME.find({},{KEY:1}); If you want to to show all document without the age field then the command is as follows > db.people.find({},{age:0});