Showing posts with label mongo. Show all posts
Showing posts with label mongo. Show all posts

Monday, October 5, 2015

MongoDB New CRUD API


The new mongodb shell includes new CRUD API! In addition to the old insert, update, and remove, the shell now supports insertMany, replaceOne, and a variety of other new methods.

> // the old insert API
> db.test.insert({_id: 1})
WriteResult({ "nInserted" : 1 })
> db.test.insert([{_id: 2}, {_id: 3}, {_id: 4}])
BulkWriteResult({
    "writeErrors" : [ ],
    "writeConcernErrors" : [ ],
    "nInserted" : 3,
    "nUpserted" : 0,
    "nMatched" : 0,
    "nModified" : 0,
    "nRemoved" : 0,
    "upserted" : [ ]
})
The new API better distinguishes single- and bulk-insert, and returns more useful results:
> // the new CRUD API
> db.test2.insertOne({_id: 1})
{
    "acknowledged" : true,
    "insertedId" : 1
}
> db.test2.insertMany([{_id: 2}, {_id: 3}, {_id: 4}])
{ 
    "acknowledged" : true,
    "insertedIds" : [ 2, 3, 4 ]
}

> // the old update API
> db.test.update(
... {_id: 1},
... {$set: {x: 1}},
... true              /* upsert */,
... false             /* multi */
)
WriteResult({
    "nMatched" : 0,
    "nUpserted" : 1,
    "nModified" : 0,
    "_id" : 1
})

> // the new update API
> db.test2.updateOne(
... {_id: 1},
... {$set: {x: 1}},
... {upsert: true}
)
{
    "acknowledged" : true,
    "matchedCount" : 0,
    "modifiedCount" : 0,
    "upsertedId" : 1
}

> // the old replace API
> db.test.update(
... {_id: 1},
... {set: {x: 1}}  // OOPS!!
)
WriteResult({
    "nMatched" : 1,
    "nUpserted" : 0,
    "nModified" : 1
})
> // document was replaced
> db.test.findOne()
{ "_id" : 1, "set" : { "x" : 1 } }


> // the old delete API
> db.test.remove({})  // remove EVERYTHING!!

> // the new delete API
> db.test2.deleteOne({})
{ "acknowledged" : true, "deletedCount" : 1 }
> db.test2.deleteMany({})
{ "acknowledged" : true, "deletedCount" : 3 }
Read more on 
https://www.mongodb.com/blog/post/consistent-crud-api-next-generation-mongodb-drivers

Monday, February 9, 2015

Meet new MongoDb - MongoDb3.0


This release marks the beginning of a new phase in which we build on an increasingly mature foundation to deliver a database so powerful, flexible, and easy to manage that it can be the new DBMS standard for any team, in any industry.

MongoDB 3.0 brings with it massive improvements to performance and scalability, enabled by comprehensive improvements in the storage layer. We have built in the WiredTiger storage engine, an incredible technology with a distinguished pedigree. WiredTiger was engineered with latch-free, non-blocking algorithms to take advantage of trends in modern hardware, like large on-chip caches and heavily threaded architectures. By drawing on both academic research and their extensive commercial experience, the WiredTiger team built a storage engine that can underpin the next 20 years of data storage applications.

With WiredTiger, MongoDB 3.0 introduces document-level concurrency control, so performance remains fast and predictable under concurrent, write-intensive workloads. Transparent on-disk compression reduces storage requirements by up to 80%, and a choice of compression algorithms means that developers can tailor the performance/space trade-off to suit the needs of particular components in their applications.

Read more on https://www.mongodb.com/blog/post/announcing-mongodb-30


MongoDB 3.0 will be generally available in March, when we finish putting it through its paces. Stay tuned for our latest release candidate, we would love it if you would try it out and give us feedback.

Monday, March 4, 2013

PyMongo ile çalışmak eğlenceli

http://blog.pythonisito.com/2012/01/moving-along-with-pymongo.html

Pymongo ile çalışmak inanılmaz eğlenceli.

pip install pymongo
veya
easy_install pymongo

Zaten yüklüyse güncellemek için
pip install --upgrade pymongo
veya
easy_install -U pymongo 

Yüklemede başka sorunlar yaşarsanız http://api.mongodb.org/python/current/ sayfasını inceleyin.

Hello world :

Tıpkı mongo konsolunda kullandığımız şekilde objeleri gönderebilmek harika. Nodejs dahil diğer hiç bir mongo driver'ı ile bu kadar rahat olmamıştı mongo sorguları.

import pymongo
con = pymongo.Connection()
# veya 
#from pymongo import Mongoclient
#con = MongoClient('localhost', 27017)
#bazı bağlantı parametreleri var. Şuradan görebilirsiniz : 
# http://api.mongodb.org/python/current/api/pymongo/mongo_client.html#pymongo.mongo_client.MongoClient

db = con.mytestdb
#veya 
#db = con['mytestdb']

db.testcollection.insert({"name":"hello"})
#Toplu insert işlemelrinde de objeleri array oalrak geçebilirsiniz
db.testcollection.insert([{"name":"hello"},{"name":"world"}])

#Şimdi eklediklerimizi listeleyelim
db.testcollection.find()
#Aslında bu sorgu tüm kayıtları getirmez ancak tüm kayıtları çekmeniz için size bir cursor objesi verir. 

list(db.testcollection.find())
#[{u'_id': ObjectId('51343ccd3a8c4a30eb2e01fe'), u'name': u'xyz'}, {u'_id': ObjectId('513448f73a8c4a366ad506d4'), u'name': u'hello'}, {u'_id': ObjectId('513448f73a8c4a366ad506d5'), u'name': u'world'}]

db.testcollecion.ensure_index('name')
#index oluşturma

db.testcollection.find({"name":"Hello"})

db.testcollection.find({"name":"Hello"}).explain()
#sorguyu çalıştırma mysql'deki "explain extended" gibi size sorguda indexin kullanılma durumunu verir.

db.testcollection.find({"name":"Hello"}).sort([ ('name', 1), ('otherfield', 1)])

# $set, $unset, $push, $pushAll, $addToSet, $pop,$pull, $pullAll, $rename, $bit gibi update operatorlerini rahatlıkla kullanabilirsiziniz. Bu operatorlerle ilgili detaylı bilgi http://docs.mongodb.org/manual/applications/update/#update-operators
db.testq.update({"name": "Hello"}, {"$set": {"name": "Updated"}})



pymongo tutorials : http://api.mongodb.org/python/current/tutorial.html
pymongo examples : http://api.mongodb.org/python/current/examples/index.html

Thursday, February 7, 2013

php5 MongoClient 64bit integer problem

php-mongo ve long int değerlerle (tckn gibi) çalışırken sorun yaşamamak için php dosyanız içinde
ini_set('mongo.native_long', 1);

yapabilir veya php.ini içine
[mongodb]
mongo.native_long = 1


ekleyebilirsiniz

Thursday, January 10, 2013

MongoDb ve FullText Search

Gecen Kasim ayinda gerceklesen MongoSV konferansinda MongoDb ile bir fulltext search demosu yapilmisti.
Ve bir sure bu ozellik nightly buildlere eklenmedi fakat git uzerinden takip edilebiliyordu.
Ancak artik 2.3.2 unstable versiyonu ( http://www.mongodb.org/downloads ) ile mongodb fulltext deneyimini test edebilirsiniz.


Asil onemli olan 2.4 versioyununda Stemming, Turkce destegi ve stop-words gelecek olmasi.

Tabiki bir Solr veya Elasticsearch degil ancak zaten asil amac kapsamli bir search engine olmak da degil.

Bir collection'da fulltext search aktiflestirmek icin ilk komut
db.adminCommand( { setParameter : "*", textSearchEnabled : true } );
Arama yapmayi dusundugumuz attribute icin index olusturmaliyiz. Index tipi "text"

db.tests.ensureIndex( { "summary": "text" } );
Ve arama yapmak icin

db.tests.runCommand( "text", { search: "Lorem" } );

Wednesday, November 28, 2012

(PHP) Mongo -> MongoClient

Php ile Mongo kullanirken kullandiginiz Mongo eklentisini artik kullanmayin. Zira guncellendi ve adi MongoClient oldu. Harika da oldu.

MongoClient'da en onemli degisiklikler


  1. Safe mode varsayilan olarak 'on'
  2. WriteConcern yine artik varsayilan olarak '1' geliyor. 
Yeni driver ile ilgili detaylari buradan inceleyin ve sisteminizi guncelleyin :  http://www.php.net/manual/en/class.mongoclient.php


Thursday, July 26, 2012

MongoDb 2.2 RC0 Güzel Yenilikler

MongoDb 2.2 versiyonu jira.mongo'daki konular ekseninde bir suredir beta olarak gelistiriliyordu.
Simdi gönül rahatlığıyla güncelleyip kullanabilirsiniz.
Genel yenilikler icin http://docs.mongodb.org/manual/release-notes/2.2/


En bekledigim ozellik TTL collections idi. Redis'de olan TTL index mevzusu epey ozendigimiz bir mevzuydu. Mevzunun detaylarina surdan bakabilirsiniz http://docs.mongodb.org/manual/tutorial/expire-data

Var olan indexlerinize TTL atamak istiyorsaniz silip tekrar olusturmalisiniz.
Capped collection'lar uzerinde uygulayamiyorsunuz (Capped collectionlar hala ayni havadalar. dokunulmaz ama performansli.).

Sunun gibi bir TTL index olusturabilirsiniz.
db.logs.ensureIndex( { "time": 1 }, { expireAfterSeconds: 3600 } )


- Onceki versiyonda bu islemi dakikalik calisan cron scriptlerim ile yapiyordum. Bu scriptlerim expire olmus dokumanlari grup grup siliyor ve saatte bir de collection uzerinde "repair" komutu calistiriyordu.

Onemli bir not "_id" uzerine TTL index olusturamazsiniz.

Konuyu iredelemek icin
Release Notes : http://docs.mongodb.org/manual/release-notes/2.2/
All JIRA Issues resolved in 2.2 :  https://jira.mongodb.org/secure/IssueNavigator.jspa?mode=hide&requestId=10907

Tuesday, July 3, 2012

mongodb - count embeded objects

Bir alana gore embeded objeleri saymak icin su sekilde yapiyorum

Wednesday, March 28, 2012

Close Mongo Connections!

MongoDb makinemde mongostat ile baktığımda gördüğüm connection sayısı  500 civarındaydı.
  

faults locked % idx miss %  conn   
     0      0.5          0   576   
     0      2.7          0   579   
     0      0.6          0   580   
     0      0.3          0   583   
     0      2.7          0   585   
     0      0.4          0   586



PHP tarafında sadece kapatmadığım mongodb bağlantılarını kapatarak bu sayının 30'a düştüğünü gördüm. Get performansında da beklediğim üzere büyük artış oldu.

Şu an da mongostat çıktısı

  qr|qw   ar|aw  conn       time
    0|0     0|0    34   10:40:10
    0|0     0|0    34   10:40:11
    0|0     0|0    35   10:40:12
    0|0     0|0    35   10:40:13
    0|0     0|0    35   10:40:14


Sunday, February 26, 2012

Sayfa Istatistiklerinde Neden MongoDb Kullanmali

Istatistik verileri icin ihtiyaciniz olan sey hizli bir yazma islemi ve bolca disktir ;)

Disk konusunda kolay genisletilebilmesi ve distrubuted yapisinin kolay kontrol edilmesinin yani sira su uc madde yuzunden sayfa goruntuleme gibi istatistiklerinizi MongoDb'de kullanmaniz icin iki temel neden

  • select - edit - update seklinde bir kullanimdansa $inc ile tek islem yapmaniz yeterlidir. Tek baglanti tek islem tek update. Klasik yontemle de tek insert yaparak devasa buyuklukte gunluk loglar olusturabilirsiniz tabi ardindan bunlari islersiniz. Neden olmasin. Ancak mongodb $inc performansindan vazgecmek istemezsiniz. 
  • write islemleri asenkron gerceklestiginden oldukca hizli gerceklesecektir ve loglama hizini dusurmeyecektir.

Sunday, February 19, 2012

MongDb Disk Temizligi

Ozellikle disk alaninizin neredeyse yarisini kaplayan bir veritabaniniz varsa collection sildiktan sonra mutlaka
db.repairDatabase()

calistirmayi unutmayin yoksa bos yere sildiginiz collection icin ayrilmis alan diskinizde yer kaplayacak.

Mevzu uzerine sunu da okuyun tabi http://www.mongodb.org/display/DOCS/Excessive+Disk+Space

Saturday, January 7, 2012

#mongotips 4 - list mongo collections and data sizes

db.getCollectionNames().forEach( function(c){   size = db[c].stats().storageSize; print(db[c] + ' ' +size/1024/1024) } )
ile tek tek collection'lari ve boyutlarini listelemis olursunuz. Ama suna dikkat cekeyim; toplam boyut  mongoDb dataninzin diskte kapladigi alani vermeyebilir. Ozellikle de cok fazla delete islemi yapmissaniz disk alani bosaltilmamis ancak ayrilmis olabilir. Bu sizi yaniltmasin. Bu kullanilmayan alanlari compact komutu ile optimize edebilirsiniz.



Monday, December 26, 2011

Mongotips #3 distinct count

bir alana göre unique count hesaplamak için uzun fonksiyonlar yazanları gördüm. Eğer alanınız indexlenmiş ise bence şöyle yapmanız daha kolay olurdu

db.operationsCollection.distinct("username").length;




Monday, November 21, 2011

Mongotips #1

Try to use a single connection. Try to fetch data in a single query.
So try to strore all dependent fields in a document.

Friday, November 18, 2011

MongoDb : Delete from capped collections?


MongoDb'de harika bir özellik olan "Capped Collections"[1] stream benzeri yapılar için birebir.
Capped Collections belirlenen boyutların dışına çıkıldığında otomatik olarak FIFO mantığıyla maximum boyutu koruyor, eski kayıtları atıyor.

Ancak bir sorun var; capped collection içerisinde silme ve güncellemem yapamıyorsunuz (boyut sabit kalırsa güncelleme yapılabiliyor aslında).

Silmek için ben de boyutu sabit tutarak dokumanın "flag" adında bir değirini "1" den "0" a değiştiriyorum.
Ancak dikkat etmeniz gereken değerin integer olmaması. Çünkü integer değer değişimi dokumanın boyutunu değiştiriyor. Ancak string "1" ile "0" dokumanda herhangi bir boyut değişimine neden olmaz.

Php ile güncelleme yapıyorsanız (string) ile cast edin.Eğer konsoldan deniyorsanız da tırnaklara dikkat edin. Tırnak ile güncelleyin.

db.stream.update({"_id" : ObjectId("4ec62adfc469885f7e000026")},{$set : {flag: "1"}})

Capped collectionlarda silme özelliğinin gelecek versiyonlar olabileceğini düşünüyorum aslında. Issue listte kabul edilmiş bir madde var ve duruyor [2].


1. Capped Collections : http://www.mongodb.org/display/DOCS/Capped+Collections
2. Issue : https://jira.mongodb.org/browse/SERVER-751

Thursday, November 17, 2011

mongo statistics tool : mongostat

Şunu da not edeyim mongodb /bin dizininde "mongostat" aracını kullanarak anlık olarak mongo istatistiklerini takip edebilirsiniz. 


Size şu değerleri verecektir.

   insert       - # of inserts per second (* means replicated op)
   query        - # of queries per second
   update       - # of updates per second
   delete       - # of deletes per second
   getmore      - # of get mores (cursor batch) per second
   command      - # of commands per second (on a slave, it's local|replicated)
   flushes      - # of fsync flushes per second
   mapped       - amount of data mmaped (total data size) megabytes
   vsize        - virtual size of process in megabytes
   res          - resident size of process in megabytes
   faults       - # of pages faults/sec (linux only)
   locked       - percent of time in global write lock
   idx miss     - percent of btree page misses (sampled)
   qr | qw      - queue lengths for clients waiting (read|write)
   ar | aw      - active clients (read|write)
   netIn        - network traffic in - bits 
   netOut       - network traffic out - bits
   conn         - number of open connections
   set          - replica set name 
   repl         - replication type 
                    M    - master
                    SEC  - secondary 
                    REC  - recovering
                    UNK  - unknown
                    SLV  - slave
                    RTR  - router


http://www.mongodb.org/display/DOCS/mongostat