Wednesday, January 7, 2015

MongoDB - Dynamic_Schema/MongoImport/Cursor/Queries/Sorting

Dynamic Schema
-Polymorphism



Schemaless / Polymorphism

--add new fields easily to schema

Things
{Shape:"Rect",x:3,y:4,Area:12}
{Shape:"Circle",radius:1,Area:3.14}


Mongo Import

Open another command prompt

mongoimport.exe can import 3 types of files CSV,TSV,JSON
mongoimport --db databasename --collection tablename < filename

mongoimport --stopOnError
mongoimport --db pcat --collection products < products.json



Mongo Shell Queries


--show recordcount
db.collection.count()
--show all rows
db.collection.find()
--Show only name column
db.collection.find({},{name:1})
--show all rows nicely
db.collection.find().toArray()
--show only 10 rows nicely 
db.collection.find({}).limit(10).toArray()
--Show only 1 row
db.collection.findOne()
db.collection.find({}).limit(1)
--Skip first 2 and give next 4
db.collection.find({}).limit(4).Skip(2)   -
--Turn off Id
db.collection.find({},{name:1,_id:0})
--Get Name and Brand
db.collection.find({},{name:1,brand:1})
--All fields and 1 row
db.collection.find({}).limit(1)
--if the output is not too big
db.collection.find({}).limit(3).toArray()
--query price = 12.5
db.collection.find({price:12.5})
db.collection.find({price:12.5}).toArray()
db.collection.find({},{price:1})


--Object id is bson type, not string
-- Get one document
db.collection.findOne({"_id": ObjectId("ddadfa5464565fgafaddadffadfadfgffd")})




db.collection.find({price:200},{name:1,price:1})

--greater than
db.collection.find({price: {$gte:200}},{name:1,price:1})

$Operators

Querying

$gte
$gt
$lt
$lte
$or
$not
$nin
$in
$type
$exists

Updating

$inc
$set
$addToSet



--greater than and expression
db.collection.find({price: {$gte:200},available:true},{name:1,price:1,available:1})

--find ac3 is in array

db.collection.find({for : "ac3"}) 


Reaching into Nested Documents

dot notation

find({"x.a":1})

Quiz

Add caption
db.collection.find({for:"ac9",Type:"case"}).toArray()

Sorting

db.collection.find(_).sort(fieldname:direction)

db.collection.find({},{name:1,price:1}).sort({price:1})

-- null is less than number

--sort rows only with price

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

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

Multiple Sort keys


db.collection.find().sort({lastname:1,firstname:1})

--SQL order by lastname,firstname

Cursors (different from other database)

db.test.find()
type it for more

db.test.find().skip(20).limit(5)

--skip is expensive, 20 is fine if 5000 is expensive.
--sort and skip is done at the server

Example

var cursor = db.test.find()
cursor.hasNext()

No comments:

Post a Comment

How to add a Database to AlwaysOn Availability Group with four different options

To add a database to an existing AlwaysOn availability group, MS has given us four options to choose from Automatic seeding Full database an...