常用的MongoDB数据表基本操作例子整理

作者:袖梨 2022-06-29

查看全部数据表

> use ChatRoom
switched to db ChatRoom
> show collections
Account
Chat
system.indexes
system.users
 

创建数据表

> db.createCollection("Account")
{"ok":1}
 

> db.createCollection("Test",{capped:true, size:10000}) { "ok" : 1 }
{"ok":1}
-- 说明

capped:true,表示该集合的结构不能被修改;

size:在建表之初就指定一定的空间大小,接下来的插入操作会不断地按顺序APPEND数据在这个预分配好空间的文件中,如果已经超出空间大小,则回到文件头覆盖原来的数据继续插入。这种结构保证了插入和查询的高效性,它不允许删除单个记录,更新的也有限制:不能超过原有记录的大小。这种表效率很高,它适用于一些暂时保存数据的场合,比如网站中登录用户的session信息,又比如一些程序的监控日志,都是属于过了一定的时间就可以被覆盖的数据。

 
修改数据表名

> db.Account.renameCollection("Account1")
{ "ok" : 1 }
 

数据表帮助主题help


> db.Account.help()
DBCollection help
        db.Account.find().help() - show DBCursor help
        db.Account.count()
        db.Account.dataSize()
        db.Account.distinct( key ) - eg. db.Account.distinct( 'x' )
        db.Account.drop() drop the collection
        db.Account.dropIndex(name)
        db.Account.dropIndexes()
        db.Account.ensureIndex(keypattern[,options]) - options is an object with these possible fields: name, unique, dropDups
        db.Account.reIndex()
        db.Account.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return.
                                                      e.g. db.Account.find( {x:77} , {name:1, x:1} )
        db.Account.find(...).count()
        db.Account.find(...).limit(n)
        db.Account.find(...).skip(n)
        db.Account.find(...).sort(...)
        db.Account.findOne([query])
        db.Account.findAndModify( { update : ... , remove : bool [, query: {}, sort: {}, 'new': false] } )
        db.Account.getDB() get DB object associated with collection
        db.Account.getIndexes()
        db.Account.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } )
        db.Account.mapReduce( mapFunction , reduceFunction , )
        db.Account.remove(query)
        db.Account.renameCollection( newName , ) renames the collection.
        db.Account.runCommand( name , ) runs a db command with the given name where the first param is the collection name
        db.Account.save(obj)
        db.Account.stats()
        db.Account.storageSize() - includes free space allocated to this collection
        db.Account.totalIndexSize() - size in bytes of all the indexes
        db.Account.totalSize() - storage allocated for all data and indexes
        db.Account.update(query, object[, upsert_bool, multi_bool])
        db.Account.validate() - SLOW
        db.Account.getShardVersion() - only for use with sharding
 

查看全部表记录

> db.Account.find()
{ "_id" : ObjectId("4df08553188e444d001a763a"), "AccountID" : 1, "UserName" : "libing", "Password" : "1", "Age" : 26, "Email" : "[email protected]", "RegisterDate" : "2011-06-09 16:31:25" }
{ "_id" : ObjectId("4df08586188e444d001a763b"), "AccountID" : 2, "UserName" : "lb", "Password" : "1", "Age" : 25, "Email" : "[email protected]", "RegisterDate" : "2011-06-09 16:36:95" }
 
--SELECT * FROM Account
 
说明:
 

默认每页显示20条记录,当显示不下的情况下,可以用it迭代命令查询下一页数据。
可以通过DBQuery.shellBatchSize设置每页显示数据的大小。如:DBQuery.shellBatchSize = 5,这样每页就显示5条记录了。

 > db.Test.find()
{ "_id" : ObjectId("4df6d55407444568af61cfea"), "TestID" : 1 }
{ "_id" : ObjectId("4df6d55907444568af61cfeb"), "TestID" : 2 }
{ "_id" : ObjectId("4df6d55b07444568af61cfec"), "TestID" : 3 }
{ "_id" : ObjectId("4df6d55e07444568af61cfed"), "TestID" : 4 }
{ "_id" : ObjectId("4df6d56207444568af61cfee"), "TestID" : 5 }
{ "_id" : ObjectId("4df6d56507444568af61cfef"), "TestID" : 6 }
{ "_id" : ObjectId("4df6d56807444568af61cff0"), "TestID" : 7 }
{ "_id" : ObjectId("4df6d56b07444568af61cff1"), "TestID" : 8 }
{ "_id" : ObjectId("4df6d56e07444568af61cff2"), "TestID" : 9 }
{ "_id" : ObjectId("4df6d57a07444568af61cff3"), "TestID" : 10 }
{ "_id" : ObjectId("4df6d57d07444568af61cff4"), "TestID" : 11 }
{ "_id" : ObjectId("4df6d58007444568af61cff5"), "TestID" : 12 }
{ "_id" : ObjectId("4df6d58307444568af61cff6"), "TestID" : 13 }
{ "_id" : ObjectId("4df6d58e07444568af61cff7"), "TestID" : 14 }
{ "_id" : ObjectId("4df6d59207444568af61cff8"), "TestID" : 15 }
{ "_id" : ObjectId("4df6d59607444568af61cff9"), "TestID" : 16 }
{ "_id" : ObjectId("4df6d59c07444568af61cffa"), "TestID" : 17 }
{ "_id" : ObjectId("4df6d5a307444568af61cffb"), "TestID" : 18 }
{ "_id" : ObjectId("4df6d5a607444568af61cffc"), "TestID" : 19 }
> DBQuery.shellBatchSize
20
> DBQuery.shellBatchSize = 5
5
> db.Test.find()
{ "_id" : ObjectId("4df6d55407444568af61cfea"), "TestID" : 1 }
{ "_id" : ObjectId("4df6d55907444568af61cfeb"), "TestID" : 2 }
{ "_id" : ObjectId("4df6d55b07444568af61cfec"), "TestID" : 3 }
{ "_id" : ObjectId("4df6d55e07444568af61cfed"), "TestID" : 4 }
{ "_id" : ObjectId("4df6d56207444568af61cfee"), "TestID" : 5 }
has more
> it
{ "_id" : ObjectId("4df6d56507444568af61cfef"), "TestID" : 6 }
{ "_id" : ObjectId("4df6d56807444568af61cff0"), "TestID" : 7 }
{ "_id" : ObjectId("4df6d56b07444568af61cff1"), "TestID" : 8 }
{ "_id" : ObjectId("4df6d56e07444568af61cff2"), "TestID" : 9 }
{ "_id" : ObjectId("4df6d57a07444568af61cff3"), "TestID" : 10 }
has more
> it
{ "_id" : ObjectId("4df6d57d07444568af61cff4"), "TestID" : 11 }
{ "_id" : ObjectId("4df6d58007444568af61cff5"), "TestID" : 12 }
{ "_id" : ObjectId("4df6d58307444568af61cff6"), "TestID" : 13 }
{ "_id" : ObjectId("4df6d58e07444568af61cff7"), "TestID" : 14 }
{ "_id" : ObjectId("4df6d59207444568af61cff8"), "TestID" : 15 }
has more
> it
{ "_id" : ObjectId("4df6d59607444568af61cff9"), "TestID" : 16 }
{ "_id" : ObjectId("4df6d59c07444568af61cffa"), "TestID" : 17 }
{ "_id" : ObjectId("4df6d5a307444568af61cffb"), "TestID" : 18 }
{ "_id" : ObjectId("4df6d5a607444568af61cffc"), "TestID" : 19 }
> it
no cursor
 

查询一条记录

> db.Account.findOne()
{
        "_id" : ObjectId("4ded95c3b7780a774a099b7c"),
        "UserName" : "libing",
        "Password" : "1",
        "Email" : "[email protected]",
        "RegisterDate" : "2011-06-07 11:06:25"
}
--SELECT TOP 1 * FROM Account
 

 查询聚集中字段的不同记录

> db.Account.distinct("UserName")
--SELECT DISTINCT("UserName")  FROM Account
 

 查询聚集中UserName包含“keyword”关键字的记录

db.Account.find({"UserName":/keyword/})
 --SELECT * FROM Account WHERE UserName LIKE '%keyword%'
 

查询聚集中UserName以"keyword" 开头的记录

> db.Account.find({"UserName":/^keyword/})
--SELECT * FROM Account WHERE UserName LIKE 'keyword%'
 

查询聚集中UserName以“keyword”结尾的记录

> db.Account.find({"UserName":/keyword$/})
--SELECT * FROM Account WHERE UserName LIKE '%keyword'
 

查询聚集中指定列

> db.Account.find({},{"UserName":1,"Email":1})    --1:true
--SELECT UserName,Email FROM Account

 
 查询聚集中排除指定列

> db.Account.find({},{"UserName":0})    --0:false
 
查询聚集中指定列,且Age > 20

> db.Account.find({"Age":{"$gt":20}},{"UserName":1,"Email":1})
--SELECT UserName,Email FROM Account WHERE Age > 20
 

聚集中字段排序

> db.Account.find().sort({"UserName":1}) -- 升序
> db.Account.find().sort({"UserName":-1}) --降序
--SELECT * FROM Account ORDER BY UserName ASC

--SELECT * FROM Account ORDER BY UserName DESC
 

统计聚集中记录条数

> db.Account.find().count()
--SELECT COUNT(*) FROM Account
 

统计聚集中符合条件的记录条数

> db.Account.find({"Age":{"$gt":20}}).count()
-- SELECT COUNT(*) FROM Account WHERE Age > 20
 

统计聚集中字段符合条件的记录条数

> db.Account.find({"UserName":{"$exists":true}}).count()
--SELECT COUNT(UserName) FROM Account
 

查询聚集中前5条记录


> db.Account.find().limit(5)
--SELECT TOP 5 * FROM Account  

查询聚集中第10条以后的记录

> db.Account.find().skip(10)
--SELECT * FROM Account WHERE AccountID NOT IN (SELECT TOP 10 AccountID FROM Account)
 
查询聚集中第10条记录以后的5条记录

> db.Account.find().skip(10).limit(5)
--SELECT TOP 5 * FROM Account WHERE AccountID NOT IN (SELECT TOP 10 AccountID FROM Account)


or查询

> db.Account.find({"$or":[{"UserName":/keyword/},{"Email":/keyword/}]},{"UserName":true,"Email":true})
--SELECT UserName,Email FROM Account WHERE UserName LIKE '%keyword%' OR Email LIKE '%keyword%'
 

添加新记录

> db.Account.insert({AccountID:2,UserName:"lb",Password:"1",Age:25,Email:"[email protected]",RegisterDate:"2011-06-09 16:36:95"})

修改记录

> db.Account.update({"AccountID":1},{"$set":{"Age":27,"Email":"[email protected]"}})
> db.Account.find({"AccountID":1})
{ "AccountID" : 1, "Age" : 27, "Email" : "[email protected]", "Password" : "1", "RegisterDate" : "2011-06-09 16:31:25", "UserName" : "libing", "_id" : ObjectId("4df08553188e444d001a763a") }
 
> db.Account.update({"AccountID":1},{"$inc":{"Age":1}})
> db.Account.find({"AccountID":1})
{ "AccountID" : 1, "Age" : 28, "Email" : "[email protected]", "Password" : "1", "RegisterDate" : "2011-06-09 16:31:25", "UserName" : "libing", "_id" : ObjectId("4df08553188e444d001a763a") }
 

删除记录

> db.Account.remove({"AccountID":1}) --DELETE FROM Account WHERE AccountID = 1

> db.Account.remove({"UserName":"libing"}) --DELETE FROM Account WHERE UserName = 'libing'
> db.Account.remove({"Age":{$lt:20}}) --DELETE FROM Account WHERE Age < 20
> db.Account.remove({"Age":{$lte:20}}) --DELETE FROM Account WHERE Age <= 20
> db.Account.remove({"Age":{$gt:20}}) --DELETE FROM Account WHERE Age > 20
> db.Account.remove({"Age":{$gte:20}}) --DELETE FROM Account WHERE Age >= 20
> db.Account.remove({"Age":{$ne:20}}) --DELETE FROM Account WHERE Age != 20
 

> db.Account.remove()    --全部删除
> db.Account.remove({})  --全部删除

相关文章

精彩推荐