Wednesday, January 18, 2017

Import

mongoimport --drop -d pcat -c products products.json

Cursor

{
var cursor = db.test.find().limit(100);
while(cursor.hasNext())
{
print("x:" + cursor.next().x);
}
}

Help usage

Help usage

db.products.find().help()

A MongoDB sharded cluster

A MongoDB sharded cluster consists of the following components:


shard: Each shard contains a subset of the sharded data. Each shard can be deployed as a replica set.
mongos: The mongos acts as a query router, providing an interface between client applications and the sharded cluster.
config servers: Config servers store metadata and configuration settings for the cluster. As of MongoDB 3.2, config servers can be deployed as a replica set.

Diagram of a sample sharded cluster for production purposes.  Contains exactly 3 config servers, 2 or more ``mongos`` query routers, and at least 2 shards. The shards are replica sets.


Development Configuration

For testing and development, you can deploy a sharded cluster with a minimum number of components. These non-production clusters have the following components:
Diagram of a sample sharded cluster for testing/development purposes only.  Contains only 1 config server, 1 ``mongos`` router, and at least 1 shard. The shard can be either a replica set or a standalone ``mongod`` instance.

Creating NEW collection TEST and inserting 20k records using FOR LOOP & LIMIT, SKIP & Sort combination OUTPUT

Creating NEW collection TEST and inserting 20k records using FOR LOOP

for(var i=0; i<20000; i++) {db.test.insert({x:i, y:"hi"});}

show collections

test

db.test.count()
20000


SKIP/LIMIT/SORT combination

db.test.find().limit(7)
db.test.find().skip(20).limit(5)
db.test.find().sort({x:-1}.skip(20).limit(5)

var query=db.test.find().sort({x:-1}.skip(20).limit(5)
query


Eg:

Write a query that retrieves documents of type "exam", sorted by score in descending order, skipping the first 50 and showing only the next 20.
db.scores.find({type:"exam"}).sort({score:-1}).skip(50).limit(20)

Select prices in ascending/Decending order where price exist

Select prices in ascending order where price exist

Asending:

db.products.find({price.{$exists.true}},(name:1,price:1}.sort({price:1})


Decending:

db.products.find({price.{$exists.true}},(name:1,price:1}.sort({price:-1})


Order by 2 fields:

db.customer.find().sort({lastname:1, first:1}) order by lastname, firstname


Order by 2 fields:

db.books.find().sort({author:1, date_posted:-1})