Find objects between two dates in MongoDB?

baacloud免费翻墙vpn注册使用

来源: Find objects between two dates in MongoDB?

Use operator gteandgteandlt to find objects between two dates in MongoDB. To understand these operators, let us create a collection.

Creating a collection here:

>db.order.insert({"OrderId":1,"OrderAddrees":"US","OrderDateTime":ISODate("2019-02-19")};
WriteResult({ "nInserted" : 1 })

>db.order.insert({"OrderId":2,"OrderAddrees":"UK","OrderDateTime":ISODate("2019-02-26")};
WriteResult({ "nInserted" : 1 })

Display all documents from the collection with the help of find() method. The query is as follows:

> db.order.find().pretty();

The following is the output:

{
   "_id" : ObjectId("5c6c072068174aae23f5ef57"),
   "OrderId" : 1,
   "OrderAddrees" : "US",
   "OrderDateTime" : ISODate("2019-02-19T00:00:00Z")
}
{
   "_id" : ObjectId("5c6c073568174aae23f5ef58"),
   "OrderId" : 2,
   "OrderAddrees" : "UK",
   "OrderDateTime" : ISODate("2019-02-26T00:00:00Z")
}

Here is the query to find objects between two dates:

> db.order.find({"OrderDateTime":{ $gte:ISODate("2019-02-10"), $lt:ISODate("2019-02-21") }
}).pretty();

The following is the output:

{
   "_id" : ObjectId("5c6c072068174aae23f5ef57"),
   "OrderId" : 1,
   "OrderAddrees" : "US",
   "OrderDateTime" : ISODate("2019-02-19T00:00:00Z")
}
赞(0) 打赏
分享到: 更多 (0)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏