How to find all objects created before specified Date in MongoDB?

MongoDBDatabaseBig Data Analytics

You can use $lt operator for this. Let us create a collection with documents −

> db.beforeSpecifyDateDemo.insertOne({"UserLoginDate":new ISODate('2016-03-21')});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbd91e4de8cc557214c0e0d")
}
> db.beforeSpecifyDateDemo.insertOne({"UserLoginDate":new ISODate('2016-05-11')});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbd91ecde8cc557214c0e0e")
}
> db.beforeSpecifyDateDemo.insertOne({"UserLoginDate":new ISODate('2017-01-31')});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbd91f9de8cc557214c0e0f")
}
> db.beforeSpecifyDateDemo.insertOne({"UserLoginDate":new ISODate('2018-05-15')});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbd9206de8cc557214c0e10")
}
> db.beforeSpecifyDateDemo.insertOne({"UserLoginDate":new ISODate('2019-04-01')});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbd9211de8cc557214c0e11")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5cbd91e4de8cc557214c0e0d"),
   "UserLoginDate" : ISODate("2016-03-21T00:00:00Z")
}
{
   "_id" : ObjectId("5cbd91ecde8cc557214c0e0e"),
   "UserLoginDate" : ISODate("2016-05-11T00:00:00Z")
}
{
   "_id" : ObjectId("5cbd91f9de8cc557214c0e0f"),
   "UserLoginDate" : ISODate("2017-01-31T00:00:00Z")
}
{
   "_id" : ObjectId("5cbd9206de8cc557214c0e10"),
   "UserLoginDate" : ISODate("2018-05-15T00:00:00Z")
}
{
   "_id" : ObjectId("5cbd9211de8cc557214c0e11"),
   "UserLoginDate" : ISODate("2019-04-01T00:00:00Z")
}

Following is the query to find all objects created before specified date −

> db.beforeSpecifyDateDemo.find({UserLoginDate: { "$lt": ISODate("2017-01-31") }});

This will produce the following output −

{ "_id" : ObjectId("5cbd91e4de8cc557214c0e0d"), "UserLoginDate" : ISODate("2016-03-21T00:00:00Z") }
{ "_id" : ObjectId("5cbd91ecde8cc557214c0e0e"), "UserLoginDate" : ISODate("2016-05-11T00:00:00Z") }
raja
Published on 02-May-2019 07:36:34
Advertisements