我正在尝试将n的唯一日期(比如2000多条记录)传递给前端,为用户提供mm/yyyy
列表以按月选择记录。
然后我需要将它们选择的月份作为ID(当前格式为mm-yyyy
)传递给后端,然后仅查询该月/年中的那组记录。
我能够获得所有记录的所有不同月份/年份。但现在我需要传递month/year
作为参数。
我的问题是:如何查询与指定月份/年匹配的所有记录?
我之前发布了一些similar,其中user3100115建议使用$redact。
Docs说要传递一年,{ $match: { year: 2014 } },
,我假设你也可以用月份来做。但后来并没有真正理解它的“编辑”部分。
所以我只是尝试使用$ match和year获取所有记录:
db.mycollection.aggregate( { $match: { year: 2015 } } );
没有返回任何内容,因为我的文档中没有简单的year
字段...而是格式为ISO的date
。
我试过
var query = Order.aggregate(
{
$project:
{
year :
{
$year: '$date'
},
month:
{
$month: '$date'
}
}
},
{
$match:
{
year : year,
month: month
}
}
);
但这不会返回文档对象,只返回_id,month,year:
{ _id: 'someid',
year: 2015,
month: 3 },
{ _id: 'someid',
year: 2015,
month: 3 },
答案 0 :(得分:2)
正如我所提到的,最好的方法是使用$redact
运算符。
db.mycollection.aggregate([
{ "$redact": {
"$cond": [
{ "$and": [
{ "$eq": [ { "$year": "$date" }, 2015 ] },
{ "$eq": [ { "$month": "$date" }, 3 ] }
] },
"$$KEEP",
"$$PRUNE"
] }
}
])
答案 1 :(得分:1)
首先,您需要使用$project从ISODate字段中取出年份和月份。然后你可以对预测值进行$match。下面的内容可能会给你一个想法。
$ created_at是MongoDB中的ISODate字段。
db.test.aggregate(
{ "$project": {
"year":{"$year":"$created_at"},
"month":{"$month":"$created_at"},
},
{ "$match":{
"year" :2015,
"month": 3
}
})
如果返回的结果需要更多字段,可以将这些字段添加到项目中,或者尝试使用mongodb $where子句。
db.test.find({$where : function() { return (this.date.getMonth() == 11 && this.date.getYear() == 2014)} })
注意:使用$ where可能会非常慢。