导航栏: 首页 评论列表

mongodb 的一些操作

默认分类 2013-06-07 11:52:54

原文地址:http://chenzhou123520.iteye.com/blog/1641319,http://blog.csdn.net/elvis_kwok/article/details/7604486

mongoexport -d xiangqu -c tags -o tags.dat
mongoimport -d xiangqu -c tags tags.dat

在使用MongoDB的时候,经常会用到MongoDB的删除操作,以下是我在使用MongoDB删除操作的总结
首先是删除用户: db.removeUser("用户名")
其次是删除数据库: db.dropDataBase() ,这个操作会删除你当前正在使用的数据库。
然后是删除集合: db.集合名.drop(),这个操作十分方便,直接把整个集合删除掉。
还有就是删除指定集合内的文档:db.集合名.remove(),remove是用来从数据库中永久删除文档。如果没有指定参数,它会删除指定结合的所有文档。我们可以给它提供参数,以删除限定的文档,例如,假设要删除blog集合一个title为mongo的文档,我们可以执行以下操作:db.blog.remove({title:"mongo"}),这类语句经常会用到。
最后是在数据集中删除一条数据:db.linlin.remove(query),适用于linlin数据集的删除操作。
一、导出工具mongoexport
Mongodb中的mongoexport工具可以把一个collection导出成JSON格式或CSV格式的文件。可以通过参数指定导出的数据项,也可以根据指定的条件导出数据。mongoexport具体用法如下所示:
参数说明:
-h:指明数据库宿主机的IP
-u:指明数据库的用户名
-p:指明数据库的密码
-d:指明数据库的名字
-c:指明collection的名字
-f:指明要导出那些列
-o:指明到要导出的文件名
-q:指明导出数据的过滤条件
1.直接导出数据到文件中
[root@localhost mongodb]# mongoexport -d test -c students -o students.dat
connected to: 127.0.0.1
exported 9 records
命令执行完后使用ll命令查看,发现目录下生成了一个students.dat的文件
参数说明:
-d:指明使用的库,本例中为test
-c:指明要导出的集合,本例中为students
-o:指明要导出的文件名,本例中为students.dat
从上面的结果可以看出,我们在导出数据时没有显示指定导出样式 ,默认导出了JSON格式的数据。如果我们需要导出CSV格式的数据,则需要使用--csv参数,具体如下所示:
Shell代码 收藏代码
[root@localhost mongodb]# mongoexport -d test -c students --csv -f classid,name,age -o students_csv.dat
参数说明:
-csv:指明要导出为csv格式
-f:指明需要导出classid、name、age这3列的数据
由上面结果可以看出,mongoexport成功地将数据根据csv格式导出到了students_csv.dat文件中。
二、导入工具mongoimport
Mongodb中的mongoimport工具可以把一个特定格式文件中的内容导入到指定的collection中。该工具可以导入JSON格式数据,也可以导入CSV格式数据。具体使用如下所示:
参数说明:
-h:指明数据库宿主机的IP
-u:指明数据库的用户名
-p:指明数据库的密码
-d:指明数据库的名字
-c:指明collection的名字
-f:指明要导入那些列
示例:先删除students中的数据,并验证
Js代码 收藏代码

db.students.remove()
db.students.find()
然后再导入上面导出的students.dat文件中的内容
Shell代码 收藏代码
[root@localhost mongodb]# ./bin/mongoimport -d test -c students students.dat
connected to: 127.0.0.1
imported 9 objects
[root@localhost mongodb]#
参数说明:
-d:指明数据库名,本例中为test
-c:指明collection名,本例中为students
students.dat:导入的文件名
上面演示的是导入JSON格式的文件中的内容,如果要导入CSV格式文件中的内容,则需要通过--type参数指定导入格式,具体如下所示:
先删除数据
db.students.remove()
db.students.find()
再导入之前导出的students_csv.dat文件
[root@localhost mongodb]# ./bin/mongoimport -d test -c students --type csv --headerline --file students_csv.dat
connected to: 127.0.0.1
imported 10 objects
[root@localhost mongodb]#
参数说明:
-type:指明要导入的文件格式
-headerline:指明第一行是列名,不需要导入
-file:指明要导入的文件
查询students集合,验证导入是否成功:


>> 留言评论