您的位置:首页 > 数据库 > Mongodb

MongoDB简易安装与操作

2010-09-02 14:21 465 查看
安装及启动服务:
 
1.解压:tar -xvf mongodb-linux-i686-1.4.4.tgz
 
2.为mongoDB创建数据目录:sudo mkdir -p /data/db/
 
3.设置/data/db访问权限:sudo chown 'id -u' /data/db
 
4.启动mongoDB服务:cd mongodb-linux-i686-1.4.4/bin
 
5.               ./mongod
 
操作数据库:
6.打开另一终端,并确保在mongoDB的bin目录:./mongo
 
   1.  超级用户相关:
         1. use admin
         2. #增加或修改用户密码
         3. db.addUser('name','pwd')
         4. #查看用户列表
         5. db.system.users.find()
         6. #用户认证
         7. db.auth('name','pwd')
         8. #删除用户
         9. db.removeUser('name')
        10. #查看所有用户
        11. show users
        12. #查看所有数据库
        13. show dbs
        14. #查看所有的collection
        use dbs
        15. show collections
        16. #查看各collection的状态
        17. db.printCollectionStats()
        18. #查看主从复制状态
        19. db.printReplicationInfo()
        20. #修复数据库
        21. db.repairDatabase()
        22. #设置记录profiling,0=off 1=slow 2=all
        23. db.setProfilingLevel(1)
        24. #查看profiling
        25. show profile
        26. #拷贝数据库
        27. db.copyDatabase('mail_addr','mail_addr_tmp')
        28. #删除collection
        29. db.mail_addr.drop()
        30. #删除当前的数据库
        31. db.dropDatabase()
   2. 客户端连接
       
   3. 增删改
         1. #存储嵌套的对象
         2. db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})
         3. #存储数组对象
         4. db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
         5. #根据query条件修改,如果不存在则插入,允许修改多条记录
         6. db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
         7. #删除yy=5的记录
         8.
1113e
db.foo.remove({'yy':5})
         9. #删除所有的记录
        10. db.foo.remove()
   4. 索引
         1. #增加索引:1(ascending),-1(descending)
         2. db.foo.ensureIndex({firstname: 1, lastname: 1}, {unique: true});
         3. #索引子对象
         4. db.user_addr.ensureIndex({'Al.Em': 1})
         5. #查看索引信息
         6. db.foo.getIndexes()
         7. db.foo.getIndexKeys()
         8. #根据索引名删除索引
         9. db.user_addr.dropIndex('Al.Em_1')
   5. 查询
         1. #查找所有
         2. db.foo.find()
         3. #查找一条记录
         4. db.foo.findOne()
         5. #根据条件检索10条记录
         6. db.foo.find({'msg':'Hello 1'}).limit(10)
         7. #sort排序
         8. db.deliver_status.find({'From':'ixigua@sina.com'}).sort({'Dt',-1})
         9. db.deliver_status.find().sort({'Ct':-1}).limit(1)
        10. #count操作
        11. db.user_addr.count()
        12. #distinct操作,查询指定列,去重复
        13. db.foo.distinct('msg')
        14. #>操作
        15. db.foo.find({"timestamp": {"$gte" : 2}})
        16. #子对象的查找
        17. db.foo.find({'address.city':'beijing'})
   6. 管理
         1. #查看collection数据的大小
         2. db.deliver_status.dataSize()
         3. #查看colleciont状态
         4. db.deliver_status.stats()
         5. #查询所有索引的大小
         6. db.deliver_status.totalIndexSize()
 
advanced queries:高级查询
db.things.find( { x : 3, y : "foo" } );
 
db.things.find({j: {$ne: 3}, k: {$gt: 10} });
 
db.things.find( { x : 3 }, { z : 1 } );
db.posts.find( { tags : 'mongodb' }, { comments : 0 } );
 
db.posts.find({}, {comments:{$slice: 5}}) // first 5 comments
db.posts.find({}, {comments:{$slice: -5}}) // last 5 comments
db.posts.find({}, {comments:{$slice: [20, 10]}}) // skip 20, limit 10
db.posts.find({}, {comments:{$slice: [-20, 10]}}) // 20 from end, limit10
 
db.collection.find({ "field" : { $gt: value } } );   // greater than  : field > value
db.collection.find({ "field" : { $lt: value } } );   // less than  :  field < value
db.collection.find({ "field" : { $gte: value } } );  // greater than or equal to : field >= value
db.collection.find({ "field" : { $lte: value } } );  // less than or equal to : field <= value
db.collection.find({ "field" : { $gt: value1, $lt: value2 } } );    // value1 < field < value
 
db.things.find( { x : { $ne : 3 } } );// Use $ne for "not equals".
 
db.collection.find( { "field" : { $in : array } } );
db.things.find({j:{$in: [2,4,6]}});
db.updates.ensureIndex( { ts : 1 } ); // ts == timestamp
var myFriends = myUserObject.friends; // let's assume this gives us an array of DBRef's of my friends
var latestUpdatesForMe = db.updates.find( { user : { $in : myFriends } } ).sort( { ts : -1 } ).limit(10);
 
db.things.find({j:{$nin: [2,4,6]}});// The $nin operator is similar to $in except that it selects objects for which the specified field does not have any value in the specified array.
 
db.things.find( "this.a % 10 == 1")
db.things.find( { a : { $mod : [ 10 , 1 ] } } )
 
{ a: [ 1, 2, 3 ] }
db.things.find( { a: { $all: [ 2, 3 ] } } );
 
db.things.find( { a : { $size: 1 } } );
 
db.things.find( { a : { $exists : true } } ); // return object if a is present
db.things.find( { a : { $exists : false } } ); // return if a is missing
 
db.things.find( { a : { $type : 2 } } ); // matches if a is a string
db.things.find( { a : { $type : 16 } } ); // matches if a is an int
Possible types are:
Type Name
Type Number
Double
1
String
2
Object
3
Array
4
Binary data
5
Object id
7
Boolean
8
Date
9
Null
10
Regular expression
11
JavaScript code
13
Symbol
14
JavaScript code with scope
15
32-bit integer
16
Timestamp
17
64-bit integer
18
Min key
255
Max key
127

db.foo.find( { $or : [ { a : 1 } , { b : 2 } ] } )
db.foo.find( { name : "bob" , $or : [ { a : 1 } , { b : 2 } ] } )
 
db.customers.find( { name : /acme.*corp/i } );// You may use regexes in database query expressions:
 
db.things.find( { colors : "red" } );// To look for the value "red" in an array field colors:
 
t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )
 
db.postings.find( { "author.name" : "joe" } );
 
 
db.customers.find( { name : { $not : /acme.*corp/i } } );
db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
 
db.myCollection.find( { a : { $gt: 3 } } );
db.myCollection.find( { $where: "this.a > 3" } );
db.myCollection.find("this.a > 3");
f = function() { return this.a > 3; } db.myCollection.find(f);
 
db.myCollection.find().sort( { ts : -1 } ); // sort by ts, descending order
 
db.students.find().limit(10).forEach( function(student) { print(student.name + "<p>"); } ); // In the shell (and most drivers), a limit of 0 is equivalent to setting no limit at all.
 
function printStudents(pageNumber, nPerPage) {
   print("Page: " + pageNumber);
   db.students.find().skip((pageNumber-1)*nPerPage).limit(nPerPage).forEach( function(student) { print(student.name + "<p>"); } );
}
 
The skip() expression allows one to specify at which object the database should begin returning results. This is often useful for implementing "paging".
 
nstudents = db.students.find({'address.state' : 'CA'}).count();
nstudents = db.students.find({'address.state' : 'CA'}).toArray().length; // VERY BAD: slow and uses excess memory
n = db.students.find().skip(20).limit(10).count(true);
 
 
db.foo.find()._addSpecial("$returnKey" , true )// only return the index key
t.find()._addSpecial( "$maxScan" , 50 )// limit the number of items to scan
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息