MongoDB Simple Select Query Example

by Didin J. on Dec 11, 2016 MongoDB Simple Select Query Example

How to select query to get required data from collection, it's similar to select query in SQL to get specific data from table.

Today I will show you a simple select query similar to standard SQL. This might feel different for who used RDMS before.

1. Basic Query

Take a look at SQL example below:

SELECT * FROM CITY

This mean all rows and fields in cities table will be returned in query results. Using MongoDB will be a little different, which the syntax will be like this:

db.city.find()

Same results will be showed and of course, they are the different format.

SQL result:

ID         |    CITI_NAME      |     PROV_NAME
===============================================
         1 | JAKARTA           | DKI JAKARTA   

MongoDB Result:

{ "_id" : ObjectId("584a13d5b65761be678d4dd4"), "citiName" : "Jakarta", "provName" : "DKI Jakarta" }

In SQL usually using INTEGER or LONG as ID with unique and incremental property and MongoDB basically using ObjectId as id.

And here's syntax comparisson:

SQL MongoDB Notes
SELECT * find() Select clause
FROM - From clause
CITY city Table/Collections Name
- db Initial mongodb syntax

2. Using Where Clause

Now we try to query city table with where clause. The scenario is getting table row which has provName "Jawa Barat".

SQL:

SELECT * FROM CITY WHERE PROV_NAME = 'JAWA BARAT'

MongoDB:

db.city.find({provName:"Jawa Barat"})

Look, MongoDB have simpler where query syntax which just adds fields to find params.

That its for now.

Thanks

The following resources might be useful for you:

Loading…