MongoDB – Queries – part1

Lets first look into the _id field that mongodb inserts with every document it inserts. _id field that mongodb inserts in immutable and unique. We can define it ourself while insert the document like following:


What about the objectOD that mongo inserts. Its a 12 byte value that has a high chance of being unique. Its based on:

  • The time the document was inserted
  • The hostname of the machine where the server is running
  • The process id of the server
  • A random incrementing number

It is made this complex so as to make it work well on a large cluster of machines where it will be difficult to keep track of single increment of ids. If your record has a createdOn field, its actually not required since the timestamp is already appended to the _id field.



You can use the new ObjectId method to get the instance. If you want to have a counter kind of thing for your application, mongo recommends to use a counter type function like as follows:

_id: "projects",
seq: 0

function getNextSequence(name) {
var ret = db.counters.findAndModify(
query: { _id: name },
update: { $inc: { seq: 1 } },
new: true

return ret.seq;

Above we created a new collections called counter and made a fucntion that will increment the count. To use it we just need to call it like following

db.projects.insert({_id: getNextSequence("projects"), name: "Project1"});


Lets delete all our previous data. To do that you need to drop all the collection using drop method like follwing:


I generated some random json data for 10 employees. There are many free online tools for that like mockaroo, generatedata etc. Once you have your data, lets import using mongoimport

mongoimport --db company --collection employees --type json --file C:\Users\Lenovo\Downloads\MOCK_EMPLOYEE_DATA.json

If you have generated data as an array use –jsonArray at the end of it.


Now that we have our data, lets do some query on it. We already know couple of methods
db.employees.find() – Will return all the records
db.employees.find().forEach(printjson) – will print the result in json format

In mongo shell, it may looks like that we get a raw output from our queries but actually we get a cursor. This will be more relevant when we use some driver with any lang like java,nodejs etc. You can actually interact with these documents there. You can filter the result by passing json key-value pair like follows

db.employees.find({“Gender”:”F”}) – Will return all Female employees
db.employees.findOne({“Gender”:”F”}) – Will return only one with formatting.
db.employees.findOne({“Gender”:”F”}).Name – Will return the Name of the employee

Note here that findOne will return only the first document it matches and since the documents are stored in natural order, which is the order in which they were inserted, the first one will be the oldest record in put collection.
db.employees.find({“Gender”:”F”}).Name – Will return nothing since find returns a cursor


Often you dont want all the fields to be returned while querying. You want to include/exclude certain fields

db.employees.find({“Gender”:”M”},{Name:1}) – Will return All males with _id and Name only
db.employees.find({“Gender”:”M”},{Name:1,DOB:true}) – Will return All males with _id,Name, DOB

1 and true are actually the same thing


As you have guessed right we can select all coumns except few like:

db.employees.find({“Gender”:”M”},{Skills:0,Email:0}) – Will return all the fields except Skills,Email

Note that you cannot mix includes and excludes together in one query as it will lead to ambiguity. The only exception to this rules is with the _id field like:

db.employees.find({“Gender”:”F”},{Name:1,DOB:1,_id:0}) – Returns only name and DOB


%d bloggers like this: