Harsh Patel
Harsh Patel

Reputation: 6830

MongoDB query based on month and date

So, I have this data in my DB,

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "from": "1970-01-01",
    "to": "1970-01-05"
  },
  {
    "_id": ObjectId("5a934e000102030405000001"),
    "from": "2017-04-18",
    "to": "2017-04-23"
  },
  {
    "_id": ObjectId("5a934e000102030405000002"),
    "from": "2018-01-29",
    "to": "2018-01-30"
  },
  {
    "_id": ObjectId("5a934e000102030405000003"),
    "from": "2018-01-02",
    "to": "2018-01-08"
  }
]

Is it possible that I pass year as 2018 and month as 01 then I get matching data from the all data? Like here I got last two Documents from collection.

I tried $elemMatch: query but didn't get expected result.

Upvotes: 2

Views: 2543

Answers (2)

Orelsanpls
Orelsanpls

Reputation: 23515

You can use a regex. Following example using mongoose :

model.find({
  from: {
     $regex: new RegExp('2018-01-', ''),
  },
});

Or

model.find({
  from: {
     $regex: /2018-01-/,
  },
});

Using mongoshell format :

db.collection.find({
  from: {
    $regex: "2018-01"
  }
})

https://mongoplayground.net/p/udRts-zp2D9

Upvotes: 2

kRiZ
kRiZ

Reputation: 815

You can also try below:

db.collection.find( 
    {"from": {"$gte": new Date(2018, 0, 1), "$lt": new Date(2018, 1, 1)}}
)

Also, do remember that that in the Date() function, the month argument starts counting at 0, not 1.

Update: MongoDB V3.4

db.collection.aggregate([
      {$project: {  "month" : {$month: '$date'}, "year" : {$year: '$date'}}},
      {$match: { month: 1, year: 2018}}
    ]);

Upvotes: 4

Related Questions