一. Mongodb
1. 导出
按条件查询并导出,命令和结果如下:
>mongoexport.exe /db primer /c post /type csv /f count,title,hush,push /o out.csv /q "{push:{$gt:27}}"
2015-08-05T08:57:52.655+0800 connected to: localhost
2015-08-05T08:57:52.669+0800 exported 1 record
需要注意的是,查询条件{push:{$gt:27}}需要使用双引号,网上很多教程都使用了单引号,在运行时会报错,错误信息如下:
2015-08-05T09:01:35.944+0800 error validating settings: query ''{push:{$gt:27
}}'' is not valid JSON: json: cannot unmarshal string into Go value of type map[
string]interface {}
2015-08-05T09:01:35.945+0800 try 'mongoexport --help' for more information
二. 使用Robomongo
Robomongo是一款mongodb的客户端程序,可以方便进行insert、update、delete等操作。
1. 查询
(1) 简单查询
查询实际很简单,双击collection,就会显示所有的记录,同时也会显示出查询命令。
例如我的collection(表)名为“post”,那么默认的命令为:
db.getCollection('post').find({})
如果要进行条件查询,只需要以json格式把查询条件写为find的参数就可以了。
例如:`db.getCollection(‘post’).find({“name”:”Tom”})`
(2)数值查询
如果涉及到数值,有关键字表示“>”、“<”、“>=”、“<=”
关键字 | 代表符号 | 含义 |
---|---|---|
$gt | great than | 大于 |
$lt | less than | 小于 |
$gte | great than or equal | 大于或等于 |
$lte | less than or equal | 小于或等于 |
这些关键词也可以出现在同一个条件里, 表示“and”
例如:db.getCollection('post').find({"push":{$gt:27}})
db.getCollection('post').find({"push":{$gt:26,$lt:30}})
代表“26<push<30”
(3)日期查询
首先要确定存储的日期格式,在Robomongo中任一日期字段右键-》Edit document,就会显示出字段的格式,一般是“ISODate”。确定格式之后,与数值查询类似,如:
db.getCollection(‘post’).find({“date”:{$lte:new ISODate(“2015-08-04”)}})
2.排序
使用sort({})进行排序,例如.sort({“name”: -1}),是指按照字段name进行降序排序。(1是升序,-1是降序)
3. 建立惟一索引
应用时常会有要求某一字段不能重复的需求,可以通过建立惟一索引来实现。
还是以“post”为例,在Robomongo中,给字段“href”建立惟一索引的命令为:
db.getCollection(‘post’).ensureIndex({‘href’:1},{unique:true})