三个数据库命令,你应该知道。

  1    show dbs – List all databases.

  2    use db_name – Switches to db_name.

  3    show collections – List all tables in the current selected database.

  1    显示DBS -列出所有的数据库。

  2    使用DB_NAME -开关DB_NAME。

  3    展示系列 -列出当前选择的数据库中的所有表。

  注意

  集合在MongoDB中,是指在SQL 表。

  4. Insert A Record

  四、插入一条记录

  要插入一条记录,使用或db.tablename.save db.tablename.insert({数据})({数据}) ,这两个动作不知道为什么MongoDB的同时创建了。

> db.users.save({username:"google",password:"google123"})
> db.users.find()
{ "_id" : ObjectId("504f45cd17f6c778042c3c07"), "username" : "mkyong", "password" : "123456" }
{ "_id" : ObjectId("504f48ea17f6c778042c3c0a"), "username" : "google", "password" : "google123" }

  五、更新记录

  要更新记录,使用:({标准},{$集:{新值}} db.tablename.update) 。在下面的例子中,用户名的密码:的“mkyong”被更新。

> db.users.update({username:"mkyong"},{$set:{password:"hello123"}})
> db.users.find()
{ "_id" : ObjectId("504f48ea17f6c778042c3c0a"), "username" : "google", "password" : "google123" }
{ "_id" : ObjectId("504f45cd17f6c778042c3c07"), "password" : "hello123", "username" : "mkyong" }

  6. Find Records

  六、查找记录

  为了找到或查询记录,使用db.tablename.find({标准}) 。

  6.1列出的所有记录表“用户”。

> db.users.find()
{ "_id" : ObjectId("504f48ea17f6c778042c3c0a"), "username" : "google", "password" : "google123" }
{ "_id" : ObjectId("504f45cd17f6c778042c3c07"), "password" : "hello123", "username" : "mkyong" }
>db.users.find()
{ “_id”:OBJECTID(“504f48ea17f6c778042c3c0a),“用户名”:“谷歌”,“密码”:“google123” }
{ “_id”:OBJECTID(“504f45cd17f6c778042c3c07” ),“密码“:“hello123” ,“用户名”:的“mkyong”}

  6.2查找记录,其中用户名是“google”

> db.users.find({username:"google"})
{ "_id" : ObjectId("504f48ea17f6c778042c3c0a"), "username" : "google", "password" : "google123" }
>db.users.find({用户名:“谷歌”})
{ “_id”:OBJECTID(“504f48ea17f6c778042c3c0a),“用户名”:“谷歌”,“密码”:“google123” }

  6.3 Find records where username’s length is less than or equal to 2

  6.3查找记录,其中username的长度小于或等于2

  6.4? Find records where username field is existed.

  6.4查找其中username字段存在的记录。

  db.users.find({username:{$exists : true}})