我为Meteor中的一个项目做了一个搜索系统,需要在两个日期之间放置一个字段来搜索。但是,日期在MongoDB中的数组中:
"relatorios" : [
{
"mes" : ISODate("2013-11-01T02:00:00Z"),
"revistas" : "2",
"brochuras" : "2",
"livros" : "0",
"folhetos" : "0",
"revisitas" : "0",
"estudos" : "0",
"horas" : "12"
},
{
"mes" : ISODate("2013-09-01T03:00:00Z"),
"revistas" : "0",
"brochuras" : "0",
"livros" : "0",
"folhetos" : "0",
"revisitas" : "0",
"estudos" : "0",
"horas" : "12"
}
]我曾尝试通过mongo直接查询筛选日期,但无法查询。我在一些论坛上读到了关于在Meteor中使用MapReduce的文章。什么是最好的选择?如果可能的话,我该怎么办?
发布于 2014-06-30 02:54:46
您可以对a和b之间的两个日期使用点表示法。
var start = new Date(450000);
var end = new Date(5450000000000);
CollectionName.find({ 'relatorios.mes' : { $gte : start, $lt: end });因此,这将得到所有文档,其中有一个数组,与此字段相匹配。记住,mongodb提取文档,所以如果您只有一个与之匹配的数组,那么它将为您提供整个文档。
发布于 2014-06-30 13:39:03
您可以使用$elemMatch找到一个数组relatorios元素,该元素在两个日期之间有一个mes值,而$位置投影运算符仅在输出中包含该匹配元素。
在外壳中:
start = new Date('2013-11-01T01:30:00Z');
end = new Date('2013-11-01T02:30:00Z');
db.test.find(
{relatorios: {$elemMatch: {mes: {$gt: start, $lt: end}}}},
{'relatorios.$': 1})如果不使用$elemMatch,那么它可以对一个元素匹配$gt,对另一个元素匹配$lt。
或者,如果您需要获取日期范围内的所有relatorios元素(而不是第一个),则可以使用aggregate
db.test.aggregate([
// Get all docs with at least one element in the date range
{$match: {relatorios: {$elemMatch: {mes: {$gt: start, $lt: end}}}}},
// Duplicate each doc, once per relatorios element.
{$unwind: '$relatorios'},
// Filter those to just the ones in the date range.
{$match: {'relatorios.mes': {$gt: start, $lt: end}}}
])发布于 2017-05-04 09:46:00
let date = new Date();
let getFirstDay = new Date(date.getFullYear(), date.getMonth() + 1, 1);
let getLastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
let firstDay = getFirstDay.getFullYear() + '-' + ((''+getFirstDay.getMonth()).length<2 ? '0' : '') + getFirstDay.getMonth() + '-' + ((''+getFirstDay.getDate()).length<2 ? '0' : '') + getFirstDay.getDate()+"T00:00:00.000Z";
let lastDay = getLastDay.getFullYear() + '-' + ((''+getLastDay.getMonth()).length<2 ? '0' : '') + (getLastDay.getMonth()+1) + '-' + ((''+getLastDay.getDate()).length<2 ? '0' : '') + getLastDay.getDate()+"T00:00:00.000Z";
var pipeline = [
{
$match: { headofficeId: headofficeId }},
{ $match: {'createdDate': {$gt: new Date(firstDay), $lt: new Date(lastDay)}}},
{$group: {_id: "$branchId", total: {$sum: "$actualValue"}}},
{ $sort: { total: -1 }
}
];
var result = Commissions.aggregate(pipeline);
return result;https://stackoverflow.com/questions/24481718
复制相似问题