Labels

Saturday, 9 January 2016

MongoDB : Basic document retrievals queries from Collection in MongoDB

Syntax to view the documents in the collection is

db.collection.find()

db - database connection window

collection - collection name

find - queries

( ) - write queries in JSON format .

Ex:

Read the records from Product collection

db.Product.find()

with the above query we cannot read or query the results in readable format so for this we need to use toArray() method

db.product.find().toArray()

Display only name document from the product collection

db.product.find({},{name:1})

Now you will see the name document details with _id value

Note : To avoid _id value we need to use _id:0 in JSON query

db.product.find({},{name:1,_id:0})

Display top 10 documents details from collection in readable format .

db.product.find().limit(10)

Display 4 documents (records) by skipping first 2 docs from product collection

db.product.find().limit(4).skip(2)

Filter the product details where price is 12.5

db.product.find({price:12.5})

Filter the product details where price is in ascending order


db.product.find().sort({price:1})

In sort 1 is Asc and -1 is Desc


How to view only one record from the Table ?

db.product.findOne()

How to display only name details from the document ?

db.product.find({},{name:1})

How to turn off displaying the ID from the collection during selection

db.product.find({},{name:1,_id:0})

How to display only name ,brand from the document

db.product.find({},{name:1,brand})

How to display only name , brand document details whose price is >=200 from product collection

db.product.find({price:{$gte:200}},{name:1,price:1})




No comments:

Post a Comment