Home mongoexport query with using date
Post
Cancel

mongoexport query with using date

Sometimes we might want to export only a specific part of our collection with query support of mongoexport.

Suppose this is our notebook collection, and each document refers to a notebook with their production date.

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",
}

The original way of mongoexport is defined by

mongoexport –db <database> –collection <collection> –query <JSON query> –out <file>

The major problem is we can not use ISODate(“”) objects to represent dates within a query, so that we have to convert each of them object into a Date object.

For instance; if we try to find the notebooks produced between 2014-03-09T22:00:00Z and 2014-03-07T22:00:00Z by Apple with the given query;

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

we will probably have an error like;

1
ERROR: too many positional options

There are two common ways to convert ISODates into Date objects which are;

  • we can use a simple javascript in mongo shell like;
  • var a = ISODate('2014-03-10T22:00:00Z');
    a.getTime()
  • we can convert the given date into milliseconds from the link ISODate to milliseconds

Now we have correct Date times to use them in our query.

1
mongoexport --db test --collection notebooks --query  "{ company:"Apple", date: { $lt: new Date(1394402400000) , $gte: new Date(1394229600000)} }" --out example.json

Finally, we will have a json file (example.json) in our current directory which includes only one document which is;

1
2
3
4
5
6
7
{
  "_id" : ObjectId("531ce460000000019b9643bd"),
  "company" : "Apple",
  "date" : ISODate("2014-03-07T22:00:00Z"),
  "price" : 2250,
  "brand" : "MacbookPro",
}
This post is licensed under CC BY 4.0 by the author.

-

RESTEasy example without using a web.xml

Comments powered by Disqus.