Zack Yang
Zack Yang

Reputation: 399

Query Mongodb on specific or range month without year of a datetime

I'm using mongodb to store datetime.

example

DB data:

[
{
  id: 1
  date: '2014-11-01T00:00:00.000Z'
},
{
  id: 2
  date: '2013-10-11T00:00:00.000Z'
},
{
  id: 3
  date: '2012-11-21T00:00:00.000Z'
}
]

filter by month 11, like query.find({'date': {$month: 11}}) should get result:

[
{
  id: 1
  date: '2014-11-01T00:00:00.000Z'
},
{
  id: 3
  date: '2012-11-21T00:00:00.000Z'
}
]

How to do that query to get what I want?

I search and got Query Mongodb on month, day, year... of a datetime, but it's not that I want, I don't want to filter the year of date.

Upvotes: 0

Views: 2996

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311925

$month is an aggregation operator, so it can only be used with aggregate, not find:

db.test.aggregate([
    {$project: {
        id: 1,
        date: 1,
        month: {$month: '$date'}
    }},
    {$match: {month: 11}},
    {$project: {
        id: 1,
        date: 1
    }}
])

Result:

{
    "result" : [ 
        {
            "_id" : ObjectId("5453d0b73712b66352662484"),
            "id" : 1,
            "date" : ISODate("2014-11-01T00:00:00.000Z")
        }, 
        {
            "_id" : ObjectId("5453d0b73712b66352662486"),
            "id" : 3,
            "date" : ISODate("2012-11-21T00:00:00.000Z")
        }
    ],
    "ok" : 1
}

Upvotes: 4

Related Questions