user944513
user944513

Reputation: 12729

how to filter data based on range of date in mongodb

[{
    "_id": {
        "$oid": "5d7a76c94c3c8c05618cef58"
    },
    "title": "hello",
    "date": {
        "$date": "2019-06-07T07:22:00.000Z"
    },
    "__v": 0
}, {
    "_id": {
        "$oid": "5d7a7809ef31980615ed3756"
    },
    "title": "hello",
    "date": {
        "$date": "2019-06-08T07:22:00.000Z"
    },
    "__v": 0
}, {
    "_id": {
        "$oid": "5d7a78e712c75706a3fdb025"
    },
    "title": "hello6",
    "date": {
        "$date": "2019-07-19T08:22:00.000Z"
    },
    "__v": 0
}, {
    "_id": {
        "$oid": "5d7a78e712c75706a3fdb025"
    },
    "title": "hello7",
    "date": {
        "$date": "2019-07-03T08:22:00.000Z"
    },
    "__v": 0
}]

I am storing my data in mongodb using mongoose like this I am trying to filter my data using mongoose

I want all document from date 2019-07-01 to 2019-07-31.can we do this filter on mongoose in mongoDB

expected output

[
{
    "_id": {
        "$oid": "5d7a78e712c75706a3fdb025"
    },
    "title": "hello6",
    "date": {
        "$date": "2019-07-19T08:22:00.000Z"
    },
    "__v": 0
}, {
    "_id": {
        "$oid": "5d7a78e712c75706a3fdb025"
    },
    "title": "hello7",
    "date": {
        "$date": "2019-07-03T08:22:00.000Z"
    },
    "__v": 0
}
]

here is my code https://codesandbox.io/s/lively-tree-hd0fo

app.get("/saveData", async () => {
  try {
    var blog = new BlogPostModel({
      title: "hello6",
      date: "19-Jul-2019 08:22"
    });
    console.log("before save");
    let saveBlog = await blog.save(); //when fail its goes to catch
    console.log(saveBlog); //when success it print.
    console.log("saveBlog save");
  } catch (error) {
    console.log(error);
  }
});

Upvotes: 0

Views: 70

Answers (1)

Caconde
Caconde

Reputation: 4483

You can use MongoDB's $gte (greater than or equal to) and $lte (lower than or equal to):

blog.find({ date: { $gte: '2019-07-01', $lte: '2019-07-31' } });

Upvotes: 1

Related Questions