Reputation: 109
Do you know if I can do a findAll
where the month of Date
is December?
I try this request but it's not good:
db.myCollection.aggregate({}, { "Date": { $month: 12 } });
it's similar to a SELECT * FROM table WHERE Months(date)=december
?
Upvotes: 2
Views: 2541
Reputation: 104
db.collection('mycollection').find({"Date": {$month: 12}})
https://docs.mongodb.com/manual/reference/method/db.collection.find/
Upvotes: 0
Reputation: 23
This should work for finding records in December for a given year, if that is enough to suit your purposes.
db.myCollection.find({
"Date":{
$gte:new Date("2016-12-01T00:00:00Z"),
$lt:new Date("2017-01-01T00:00:00Z")
}})
Upvotes: -1
Reputation: 103375
Consider running an aggregation pipeline that uses the $redact
operator as it allows you to incorporate with a single pipeline, a functionality with $project
to create a field that represents the month of a date field and $match
to filter the documents
which match the given condition of the month being December.
In the above, $redact
uses $cond
tenary operator as means to provide the conditional expression that will create the system variable which does the redaction. The logical expression in $cond
will check
for an equality of a date operator field with a given value, if that matches then $redact
will return the documents using the $$KEEP
system variable and discards otherwise using $$PRUNE
.
Running the following pipeline should give you the desired result:
db.myCollection.aggregate([
{
"$redact": {
"$cond": [
{ "$eq": [{ "$month": "$Date" }, 12] },
"$$KEEP",
"$$PRUNE"
]
}
}
])
This is similar to a $project
+$match
combo but you'd need to then select all the rest of the fields that go into the pipeline:
db.myCollection.aggregate([
{
"$project": {
"month": { "$month": "$Date" },
"field1": 1,
"field2": 1,
.....
}
},
{ "$match": { "month": 12 } }
])
With another alternative, albeit slow query, using the find()
method and $where
as:
db.myCollection.find({ "$where": "this.Date.getMonth() === 11" })
Upvotes: 3