This is the second article of the series “Learn MongoDB with Me,” and if you haven’t read my previous post on this topic, I strongly recommend you find it here. This is a continuation of exploring the Mongo shells. We will be performing some commands on the Mongo shells. For easy reference I will try to add screenshots for each of the steps I am following. I hope it will help you to come along with me. Thanks for reading. You can always read this article on my blog here.
BackgroundI believe that you have enough knowledge about Mongo DB and how to set up it, and how Mongo shells can be used. If you are not able to answer these question for yourself, please consider reading my previous posts again.
Mongo shells, the perfect CLIWe can do anything in the Mongo shell, to make a statement clear. I am going to perform some CRUD operations (Create, Read, Update, Delete) within Mongo shells. To do so, we can use Mongo import commands. The Mongo import commands can do the work for you, even if the data is in .tsv, .csv, .json etc. Let’s see those in action.
As a first step, let us see some documentation.
- C:\Program Files\MongoDB\Server\3.4\bin>mongoimport --help
The above command will give you all the options available to get started.
- Usage:
- mongoimport < options > < file >
- Import CSV, TSV or JSON data into MongoDB.If no file is provided, mongoimport reads from stdin.
- See http: //docs.mongodb.org/manual/reference/program/mongoimport/ for more information.
- general options:
- /help print usage /
- version print the tool version and
- exit
- verbosity options:
- /v, /verbose: < level > more detailed log output(include multiple times
- for more verbosity, e.g. - vvvvv,
- or specify a numeric value,
- e.g.--verbose = N) /
- quiet hide all log output
- connection options:
- /h, /host: < hostname > mongodb host to connect to(setname / host1, host2
- for replica sets) /
- port: < port > server port(can also use
- --host hostname: port)
- kerberos options:
- /gssapiServiceName:<service-name> service name to use when
- authenticating using
- GSSAPI / Kerberos('mongodb'
- by
- default) /
- gssapiHostName: < host - name > hostname to use when
- authenticating using
- GSSAPI / Kerberos(remote server 's address by default)
- ssl options:
- /ssl connect to a mongod or mongos
- that has ssl enabled /
- sslCAFile: < filename > the.pem file containing the root certificate chain from the certificate authority /
- sslPEMKeyFile: < filename > the.pem file containing the certificate and key /
- sslPEMKeyPassword: < password > the password to decrypt the sslPEMKeyFile,
- if necessary /
- sslCRLFile: < filename > the.pem file containing the certificate revocation list /
- sslAllowInvalidCertificates bypass the validation
- for server certificates /
- sslAllowInvalidHostnames bypass the validation
- for server name /
- sslFIPSMode use FIPS mode of the installed openssl library authentication options:
- /u, /username: < username > username
- for authentication /
- p, /password:<password> password for authentication /
- authenticationDatabase: < database - name > database that holds the user 's credentials /
- authenticationMechanism: < mechanism > authentication mechanism to use namespace options:
- /d, /db: < database - name > database to use /
- c, /collection:<collection-name> collection to use
- uri options:
- /uri:mongodb-uri mongodb uri connection string
- input options:
- /f, /fields: < field > [, < field > ] * comma separated list of
- fields, e.g. - f name, age /
- fieldFile: < filename > file with field names - 1 per line /
- file: < filename > file to
- import from;
- if not specified, stdin is used /
- headerline use first line in input source as the field list(CSV and TSV only) /
- jsonArray treat input source as a JSON array /
- parseGrace: < grace > controls behavior when type coercion fails - one of:
- autoCast, skipField, skipRow,
- stop(defaults to 'stop')
- (
- default: stop) /
- type: < type > input format to
- import: json,
- csv, or tsv(defaults to 'json')(
- default: json) /
- columnsHaveTypes indicated that the field list(from--fields, --fieldsFile,
- or--headerline) specifies types; They must be in the form of
- '<colName>.<type>(<arg>)'.The type can be one of: auto,
- binary, bool, date, date_go,
- date_ms, date_oracle, double,
- int32, int64, string.For each of the date types, the argument is a datetime layout string.For the binary type,
- the argument can be one of:
- base32, base64, hex.All other types take an empty argument.Only valid
- for CSV and TSV imports.e.g.zipcode.string(),
- thumbnail.binary(base64) ingest options:
- /drop drop collection before
- inserting documents /
- ignoreBlanks ignore fields with empty values in CSV and TSV /
- maintainInsertionOrder insert documents in the order of their appearance in the input source /
- j, /numInsertionWorkers:<number> number of insert operations
- to run concurrently(defaults to 1)(
- default: 1) /
- stopOnError stop importing at first insert / upsert error /
- mode: [insert | upsert | merge] insert: insert only.upsert:
- insert or replace existing documents.merge: insert or modify existing documents.defaults to insert /
- upsertFields: < field > [, < field > ] * comma - separated fields
- for the query part when--mode is set to upsert or merge /
- writeConcern: < write - concern - specifier > write concern options e.g.
- --writeConcern majority,
- --writeConcern '{w: 3,
- wtimeout: 500, fsync: true,
- j: true
- }
- ' /
- bypassDocumentValidation bypass document validation
Insert data to MondoDB using Mongo shell
Now let’s say I have the following JSON data, and we are going to insert the same to our db collection.
- [{
- "color": "black",
- "category": "hue",
- "type": "primary",
- "code": {
- "rgba": [255, 255, 255, 1],
- "hex": "#000"
- }
- },
- {
- "color": "white",
- "category": "value",
- "code": {
- "rgba": [0, 0, 0, 1],
- "hex": "#FFF"
- }
- },
- {
- "color": "red",
- "category": "hue",
- "type": "primary",
- "code": {
- "rgba": [255, 0, 0, 1],
- "hex": "#FF0"
- }
- },
- {
- "color": "blue",
- "category": "hue",
- "type": "primary",
- "code": {
- "rgba": [0, 0, 255, 1],
- "hex": "#00F"
- }
- },
- {
- "color": "yellow",
- "category": "hue",
- "type": "primary",
- "code": {
- "rgba": [255, 255, 0, 1],
- "hex": "#FF0"
- }
- },
- {
- "color": "green",
- "category": "hue",
- "type": "secondary",
- "code": {
- "rgba": [0, 255, 0, 1],
- "hex": "#0F0"
- }
- }
- ]
To do so, we need to use the following command.
- C:\Program Files\MongoDB\Server\3.4\bin>mongoimport --db mylearning --collection colors --jsonArray --file colors.json
Here, as you can see, we are providing the db name, collection, name, the data type of the file, and finally the file name.
If you ever get the error as “Failed: open colors.json: The system cannot find the file specified.”, please make sure that the document is in the server folder, in my case it is “C:\Program Files\MongoDB\Server\3.4\bin”. If everything is fine, you will be able to see the output as preceding.
- C:\Program Files\MongoDB\Server\3.4\bin>mongoimport --db mylearning --collection colors --jsonArray --file colors.json
- 2018-03-01T16:35:35.470+0530 connected to: localhost
- 2018-03-01T16:35:36.012+0530 imported 6 documents
- C:\Program Files\MongoDB\Server\3.4\bin>
Reading the data from a collection in MongoDB
Now that we have colors collection, let’s go and check whether the database has the data we are expecting.
- C: \Program Files\ MongoDB\ Server\ 3.4\ bin > mongo
- MongoDB shell version v3 .4 .9
- connecting to: mongodb: //127.0.0.1:27017
- MongoDB server version: 3.4 .9
- Server has startup warnings:
- 2018 - 03 - 01 T16: 24: 43.793 + 0530 I CONTROL[initandlisten]
- 2018 - 03 - 01 T16: 24: 43.793 + 0530 I CONTROL[initandlisten] ** WARNING: Access control is not enabled
- for the database.
- 2018 - 03 - 01 T16: 24: 43.793 + 0530 I CONTROL[initandlisten] ** Read and write access to data and configuration is unrestricted.
- 2018 - 03 - 01 T16: 24: 43.793 + 0530 I CONTROL[initandlisten]
- MongoDB Enterprise > use mylearning
- switched to db mylearning
- MongoDB Enterprise > show collections
- chats
- colors
- messages
- MongoDB Enterprise > db.colors.count
- function(query, options) {
- query = this.find(query);
- // Apply options and return the result of the find
- return QueryHelpers._applyCountOptions(query, options).count(true);
- }
- MongoDB Enterprise > db.colors.count()
- 6
- MongoDB Enterprise >
When you use count, make sure you are treating it as a function as count(). We have the count as 6, and that’s what we are expecting. Am I right? Don’t you think that we should go fetch some data from that collection with some filters?

Hadshana KamalanathanPosted Jul 14, 2018, 1:28 AM
Thanks for sharing
Sundaram SubramanianPosted Mar 4, 2018, 3:38 AM
A good work Sibeesh Venu Buddy. Keep sharing
Manav PandyaPosted Mar 2, 2018, 10:52 AM
Thanks for sharing @sibi sir