MongoDB基础语法

上一篇 / 下一篇  2014-07-03 11:16:21 / 个人分类:工具备忘录

//连接mongo服务器
mongo <ip地址>
数据库有密码时有以下两种输入用户名和密码的方式:
mongo <ip address>/database - u username -p password

mongo <ip address>
use database
db.auth("username","password")
//查看所有数据库
show dbs
//使用数据库
use <库名>
//查看集合
show collections
//查看用户
show users
//查看当前使用的数据库
db 或 db.getName()
//查看当前db的链接机器地址
db.getMongo()
//删除当前的数据库
db.dropDatabase()
db.help():显示数据库操作命令,里面有很多的命令 
db.foo.help():显示集合操作命令,同样有很多的命令,foo指的是当前数据库下,一个叫foo的集合,并非真正意义上的命令 
db.foo.find():对于当前数据库中的foo集合进行数据查找(由于没有条件,会列出所有数据) 
db.foo.find( { a : 1 } ):对于当前数据库中的foo集合进行查找,条件是数据中有一个属性叫a,且a的值为1
//查询name = zhangsan, age = 22的数据
db.userInfo.find({name: 'zhangsan', age: 22});
相当于:select * from userInfo where name = ‘zhangsan’ and age = ‘22’;
//db.userInfo.find({}, {name: 1, age: 1});
相当于:select name, age from userInfo;
当然name也可以用true或false,当用ture的情况下河name:1效果一样,如果用false就是排除name,显示name以外的列信息
//格式化显示数据
db.foo.find().limit(1).pretty()
//更新字段值
db.books.update(
   { item: "Divine Comedy" },
   {
      $set: { price: 18 },
      $inc: { stock: 5 }
   }
)
//删除一个记录
> db.collection1.remove({sid:"111",url:"http://xxx"},1)
//$in & $nin
db.tianyc02.find({age:{$in:[11,22]}})
db.tianyc02.find({age:{$nin:[11,22]}})
//$or
db.tianyc02.find({$or:[{age:11},{name:'xttt'}]})
//$gt , >= $gte, < $lt, <= $lte, != $ne
db.tianyc02.find({age:{$lt:100}})
//$not
db.tianyc02.find({age:{$mod:[11,0]}})
{ "_id" : ObjectId("50ea6b6f12729d90ce6e341b"), "name" : "xtt", "age" : 11 }
{ "_id" : ObjectId("50ea6b7312729d90ce6e341c"), "name" : "xtt", "age" : 22 }
db.tianyc02.find({age:{$not:{$mod:[11,0]}}})
{ "_id" : ObjectId("50ea6eba12729d90ce6e3423"), "name" : "xttt", "age" : 111 }
{ "_id" : ObjectId("50ea6eba12729d90ce6e3424"), "name" : "xttt", "age" : 222 }
$mod会将查询的值除以第一个给定的值,若余数等于第二个给定的值,则返回该结果。
$not与正则表达式联合使用时极为有效,用来查找那些与特定模式不匹配的文档。
//查找重复记录
db.collection1.aggregate([{ $match: { u1: "20140627" } },{$group : {_id : "$ofid", total : {$sum : 1}}},{ $match: { total: {$gt: 1} } }])
//日期字段:
db.tickets.find({"date":{$lt:ISODate("2013-01-17T01:16:33.303Z")}}).limit (5);
db.cpc_common.cpc_click_log.find({date_created:{$gte:new Date(2010,5,16)}});
//ObjectId和ISODate
{
        "_id" : ObjectId("53c383db6f2a0abfb8ea6c51"),
        "amount" : "0",
        "matchDate" : ISODate("2014-07-14T07:15:06.847Z"),
}
以_id字段查询,更新matchDate
> db.foo.update({_id:new ObjectId("53c383db6f2a0abfb8ea6c51")},{$set:{matchDate:new Date("2014-07-15T07:15:06.847Z")}})

> db.foo.update({_id:ObjectId("53c383db6f2a0abfb8ea6c51")},{$set:{matchDate:new Date("2014-07-15T07:15:06.847Z")}})

TAG:

 

评分:0

我来说两句

我的栏目

日历

« 2024-05-08  
   1234
567891011
12131415161718
19202122232425
262728293031 

数据统计

  • 访问量: 17060
  • 日志数: 17
  • 建立时间: 2014-07-01
  • 更新时间: 2014-12-15

RSS订阅

Open Toolbar