Mohan Murugesan
Mohan Murugesan

Reputation: 276

mongoose - Find by created time irrelevant of date

I have the following mongoose model

const Post = new Schema({
  created_at: { type: Date, default: Date.now() },
  updated_at: { type: Date },
  postName: String,
  postContent:String,
  promoted: {
    isPromoted: { type: Boolean, default: false, required: true },
    promotedFrom: { type: Date },
    promotedTill: { type: Date },
  },
});

Example Document

const Post = new Schema({
  created_at: 2020-07-05T16:16:38.139+00:00,
  postName: My first Post,
  postContent:This is my furst post,
  promoted: {
    isPromoted: true,
    promotedFrom: 2020-11-13T16:14:38.139+00:00,
    promotedTill: 2020-11-20T16:14:38.139+00:00,
  },
});

With mongose I want to query the documents with the promotedTill time to be between 12.00 hrs to 16.30 hrs irrespective of any date.

Thanks in Advance.

Upvotes: 0

Views: 822

Answers (2)

Buzz Moschetti
Buzz Moschetti

Reputation: 7578

Adjust the gt and lt to include/exclude boundaries:

db.foo.aggregate([
{$match: {$expr: {
            $and: [
{$gt: [ {$hour: "$promoted.promotedTill"}, 12 ]},
{$lte: [{$hour: "$promoted.promotedTill"},16]},
{$lt: [{$minute: "$promoted.promotedTill"},30]}
                    ]}
    }}

  ]);

Upvotes: 1

J.F.
J.F.

Reputation: 15187

check this example

I've done the query quite simple, without other fields.

The query is this:

db.collection.find({
  "$and": [
    {
      "promoted.promotedFrom": {
        "$gte": ISODate("yourdate")
      }
    },
    {
      "promoted.promotedTill": {
        "$lte": ISODate("yordate")
      }
    }
  ]
})

Basically is search a value within a range using $gte (greater than or equal) and $lte (lower than or equal).

Using the $and operator both conditions should be true.

Upvotes: 0

Related Questions