MongoDB – Créer une collection en environnement Shard


Cet article s’appuie sur la création de l’environnement Shard présenté dans le site.

La base de données achdb est créée et en mode Sharding.

La création d’une collection en environnement Shard comprend : la création de la collection par insertion de documents dans une base de données en Sharding, la création d’un index approprié, la mise en Shard de la collection.

Créer une Collection

[mongodb@mongodb12 datadb]$ mongo --host mongodb11 --port 27017
MongoDB shell version: 2.6.7
connecting to: mongodb11:27017/test
mongos> use achdb
switched to db achdb
mongos> db.Test1.insert({test1: "azerty","test2": 10 })
WriteResult({ "nInserted" : 1 })
mongos> db.Test1.insert({test1: "uiopqsdfg","test2": 12 })
WriteResult({ "nInserted" : 1 })

Créer un index hash sur la Collection

mongos> db.Test1.createIndex( { test1: "hashed" } )
{
 "raw" : {
 "rs0/mongodb01:27017,mongodb02:27017,mongodb03:27017" : {
 "createdCollectionAutomatically" : false,
 "numIndexesBefore" : 1,
 "numIndexesAfter" : 2,
 "ok" : 1
 }
 },
 "ok" : 1
}

Mise en Sharding de la Collection

mongos> sh.shardCollection( "achdb.Test1", { test1: "hashed" } )
{ "collectionsharded" : "achdb.Test1", "ok" : 1 }

Vérifier l’état de la base de données et de ses Collections

mongos> db.stats()
{
 "raw" : {
 "rs0/mongodb01:27017,mongodb02:27017,mongodb03:27017" : {
 "db" : "achdb",
 "collections" : 3,
 "objects" : 8,
 "avgObjSize" : 80,
 "dataSize" : 640,
 "storageSize" : 24576,
 "numExtents" : 3,
 "indexes" : 2,
 "indexSize" : 16352,
 "fileSize" : 67108864,
 "nsSizeMB" : 16,
 "dataFileVersion" : {
 "major" : 4,
 "minor" : 5
 },
 "extentFreeList" : {
 "num" : 0,
 "totalSize" : 0
 },
 "ok" : 1
 }
 },
 "objects" : 8,
 "avgObjSize" : 80,
 "dataSize" : 640,
 "storageSize" : 24576,
 "numExtents" : 3,
 "indexes" : 2,
 "indexSize" : 16352,
 "fileSize" : 67108864,
 "extentFreeList" : {
 "num" : 0,
 "totalSize" : 0
 },
 "ok" : 1
}

mongos> db.printShardingStatus()
--- Sharding Status --- 
 sharding version: {
 "_id" : 1,
 "version" : 4,
 "minCompatibleVersion" : 4,
 "currentVersion" : 5,
 "clusterId" : ObjectId("55b9d8baafcefcc18f8afae3")
}
 shards:
 { "_id" : "rs0", "host" : "rs0/mongodb01:27017,mongodb02:27017,mongodb03:27017" }
 databases:
 { "_id" : "admin", "partitioned" : false, "primary" : "config" }
 { "_id" : "test", "partitioned" : false, "primary" : "rs0" }
 { "_id" : "achdb", "partitioned" : true, "primary" : "rs0" }
 achdb.Test1
 shard key: { "test1" : "hashed" }
 chunks:
 rs0 1
 { "test1" : { "$minKey" : 1 } } -->> { "test1" : { "$maxKey" : 1 } } on : rs0 Timestamp(1, 0) 
 { "_id" : "db", "partitioned" : false, "primary" : "rs0" }
 { "_id" : "records", "partitioned" : false, "primary" : "rs0" }