搭建环境 环境为win8 x64,下载安装省略。之后将mongodb 的bin目录加入windows的path中,为以后使用方便。 c盘新建存储文件夹:c:/data/db 运行服务:WIN+R,输入mongod.exe --dbpath c:/data/db 回车,此窗口不要关闭 启动客户端:WIN+R,输入mongo 回车 数
搭建环境
环境为win8 x64,下载安装省略。之后将mongodb 的bin目录加入windows的path中,为以后使用方便。
c盘新建存储文件夹:c:/data/db
运行服务:WIN+R,输入mongod.exe --dbpath c:/data/db 回车,此窗口不要关闭
启动客户端:WIN+R,输入mongo 回车
数据库操作
查看当前数据库名:db
查看所有数据库: show dbs 或show databases
切换数据库: use mydb
切换数据库:use mydb
数据操作
插入
创建数据: j={name:'mongo'}
k={x:3}
插入指定集合: db.testData.insert(j);
db.testData.insert(k);
查看当前数据库中有哪些集合: show collections
查看指定集合中的所有数据(每次显示20条,输入it显示接下来20条): db.testData.find();
通过JavaScript的for循环插入多条数据:
for(var i=0;i
db.testData.insert({num:i,name:'name'+i})
}
mongodb的Javascript控制台可以直接输入JavaScript代码执行,类似nodejs的控制台。
查询
查询指针
当查询集合时,mongodb返回一个包含查询结果集的指针对象
var c = db.testData.find();
遍历该指针对象:
while(c.hasNext()) printjson(c.next());
使用指针数组
将指针对象直接作为数组使用
printjson(c[4]);
当使用以上方式访问指针内容时,mongo实现调用了cursor.toArray()方法,从内存中加载指针返回的数据, 再将其作为数组访问。
这个操作将完全的遍历整个指针,对于非常大的结果集,可能内存溢出。
条件查询
查询指定字段的记录
db.testData.find({num:5});
查询单条记录(若是有多条,返回第一条)
db.testData.findOne({num:5});
指定结果集包含记录条数
db.testData.find().limit(5);
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn