有时,我们可能想使用mongoexport的查询参数导出集合的某一特定部分。
主要的问题是在查询中不能使用ISODate("")对象作为时间的查询条件,必须转换成Date对象。
最后会在当前文件夹下得到一个json文件,只包含一个文档记录;
例如,一个notebook集合(collection),每个notebook文档(document)的文档都有一个生产日期属性。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
{
"_id"
: ObjectId("531ce460000000019b9643bc"),
"company"
: "Samsung",
"date"
: ISODate("2014-03-09T22:00:00Z"),
"price"
: 2000,
"brand"
: "Ultrabook",
}
{
"_id"
: ObjectId("531ce460000000019b9643ba"),
"company"
: "Sony",
"date"
: ISODate("2014-03-08T22:00:00Z"),
"price"
: 1500,
"brand"
: "Vaio",
}
{
"_id"
: ObjectId("531ce460000000019b9643bd"),
"company"
: "Apple",
"date"
: ISODate("2014-03-07T22:00:00Z"),
"price"
: 2250,
"brand"
: "MacbookPro",
}
{
"_id"
: ObjectId("531ce460000000019b9643be"),
"company"
: "Apple",
"date"
: ISODate("2014-03-06T22:00:00Z"),
"price"
: 1200,
"brand"
: "MacbookAir",
}
{
"_id"
: ObjectId("531ce460000000019b9643bf"),
"company"
: "Samsung",
"date"
: ISODate("2014-03-05T22:00:00Z"),
"price"
: 1000,
"brand"
: "Ultrabook",
}
|
mongoexport的定义如下:
1
|
mongoexport
--db
<database>
--collection
<collection>
--query
<JSON query>
--out
<file>
|
例如,我们要查找生产日期位于2014-03-09T22:00:00Z 和 2014-03-07T22:00:00Z之间的苹果公司的笔记本(notebook);
1
|
mongoexport
--db test
--collection notebooks
--query '{ company:"Apple", date: { $lt: ISODate("2014-03-09T22:00:00Z") , $gte: ISODate("2014-03-07T22:00:00Z")} }'
--out example.json
|
将得到以下错误:
ERROR
ERROR: too many positional options
有两种方法可以把ISODate对象转成Date对象,方法如下:
(1)使用mongo shell中的javascript脚本;
- 12var a = ISODate('2014-03-10T22:00:00Z');a.getTime()
(2)把 ISODate数据转成毫秒,然后在转成Date对象;
>ISODate("2014-03-10T22:00:00Z").valueOf()
现在可以使用正确的Date时间进行查询:
1
|
mongoexport
--db test
--collection notebooks
--query "{ company:"Apple", date: { $lt: new Date(1394402400000) , $gte: new
Date(1394229600000)} }" --out
example.jso
|
1
2
3
4
5
6
7
|
{
"_id"
: ObjectId("531ce460000000019b9643bd"),
"company"
: "Apple",
"date"
: ISODate("2014-03-07T22:00:00Z"),
"price"
: 2250,
"brand"
: "MacbookPro",
}
|
原文地址:http://www.buraktas.com/mongoexport-query-with-using-date/