- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
假设我有以下查询:
post.getSpecificDateRangeJobs = function(queryData, callback) {
var matchCriteria = queryData.matchCriteria;
var currentDate = new Date();
var match = { expireDate: { $gte: new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate()) } };
if (queryData.matchCriteria !== "") {
match = {
expireDate: { $gte: new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate()) },
$text: { $search: matchCriteria }
};
}
var pipeline = [
{
$match: match
},
{
$group: {
_id: null,
thirtyHourAgo: {
$sum: {
$cond: [
{
$gte: [
"$publishDate",
new Date(queryData.dateGroups.thirtyHourAgo)
]
},
1,
0
]
}
},
fourtyEightHourAgo: {
$sum: {
$cond: [
{
$gte: [
"$publishDate",
new Date(queryData.dateGroups.fourtyHourAgo)
]
},
1,
0
]
}
},
thirtyDaysAgo: {
$sum: {
$cond: [
{
$lte: [
"$publishDate",
new Date(queryData.dateGroups.oneMonthAgo)
]
},
1,
0
]
}
}
}
}
];
var postsCollection = post.getDataSource().connector.collection(
post.modelName
);
postsCollection.aggregate(pipeline, function(err, groupByRecords) {
if (err) {
return callback("err");
}
return callback(null, groupByRecords);
});
};
我想做的是:1- 检查 queryData.dateGroups.thirtyHourAgo
是否存在并具有值(value),然后只在查询中添加相关的匹配子句(仅过去 30 小时的帖子计数)。2- 检查 queryData.dateGroups.fourtyHourAgo
是否存在,然后添加相关查询部分(过去 30 小时和过去 48 小时前的帖子计数)。3 和 queryData.dateGroups.oneMonthAgo
相同(过去 30 小时、48 小时和过去一个月的帖子数)。
我需要类似 Mysql 的 if 条件来检查变量是否存在且不为空,然后包含一个查询子句。有可能吗?
我的样本数据是这样的:
/* 1 */
{
"_id" : ObjectId("58d8bcf01caf4ebddb842855"),
"vacancyNumber" : "123213",
"position" : "dsfdasf",
"number" : 3,
"isPublished" : true,
"publishDate" : ISODate("2017-03-11T00:00:00.000Z"),
"expireDate" : ISODate("2017-05-10T00:00:00.000Z"),
"keywords" : [
"dasfdsaf",
"afdas",
"fdasf",
"dafd"
],
"deleted" : false
}
/* 2 */
{
"_id" : ObjectId("58e87ed516b51f33ded59eb3"),
"vacancyNumber" : "213123",
"position" : "Software Developer",
"number" : 4,
"isPublished" : true,
"publishDate" : ISODate("2017-04-14T00:00:00.000Z"),
"expireDate" : ISODate("2017-05-09T00:00:00.000Z"),
"keywords" : [
"adfsadf",
"dasfdsaf"
],
"deleted" : false
}
/* 3 */
{
"_id" : ObjectId("58eb5b01c21fbad780bc74b6"),
"vacancyNumber" : "2432432",
"position" : "Web Designer",
"number" : 4,
"isPublished" : true,
"publishDate" : ISODate("2017-04-09T00:00:00.000Z"),
"expireDate" : ISODate("2017-05-12T00:00:00.000Z"),
"keywords" : [
"adsaf",
"das",
"fdafdas",
"fdas"
],
"deleted" : false
}
/* 4 */
{
"_id" : ObjectId("590f04fbf97a5803636ec66b"),
"vacancyNumber" : "4354",
"position" : "Software Developer",
"number" : 5,
"isPublished" : true,
"publishDate" : ISODate("2017-05-19T00:00:00.000Z"),
"expireDate" : ISODate("2017-05-27T00:00:00.000Z"),
"keywords" : [
"PHP",
"MySql"
],
"deleted" : false
}
假设我的应用程序界面中有三个链接:1- 30 小时前的帖子。2- 48 小时前的帖子。3- 最后一个月的帖子。
现在,如果用户点击第一个链接,我应该控制只对 30 小时前的帖子进行分组,但是如果用户点击第二个链接,我应该准备查询以对 30 小时和 48 小时的帖子进行分组,如果用户单击第三个链接,我应该为所有这些做好准备。
我想要这样的东西:
var pipeline = [
{
$match: match
},
{
$group: {
_id: null,
if (myVariable) {
thirtyHourAgo: {
........
........
}
}
if (mysecondVariable) {
fortyEightHourAgo: {
........
........
}
}
最佳答案
您可以使用 javascript 根据您的查询参数动态创建 json 文档。
更新后的函数看起来像
post.getSpecificDateRangeJobs = function(queryData, callback) {
var matchCriteria = queryData.matchCriteria;
var currentDate = new Date();
// match document
var match = {
"expireDate": {
"$gte": currentDate
}
};
if (matchCriteria !== "") {
match["$text"]: {
"$search": matchCriteria
}
};
// group document
var group = {
_id: null
};
// Logic to calculate hours difference between current date and publish date is less than 30 hours.
if (queryData.dateGroups.thirtyHourAgo) {
group["thirtyHourAgo"] = {
"$sum": {
"$cond": [{
"$lte": [{
"$divide": [{
"$subtract": [currentDate, "$publishDate"]
}, 1000 * 60 * 60]
}, 30]
},
1,
0
]
}
};
}
// Similarly add more grouping condition based on query params.
var postsCollection = post.getDataSource().connector.collection(
post.modelName
);
// Use aggregate builder to create aggregation pipeline.
postsCollection.aggregate()
.match(match)
.group(group)
.exec(function(err, groupByRecords) {
if (err) {
return callback("err");
}
return callback(null, groupByRecords);
});
};
关于node.js - Mongoose 如何编写带if条件的查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43889978/
当我保存4条记录时,我需要将它们一一保存,所以我的代码是 a.save(function(){ b.save(function(){ c.save(function(){ d.save(f
Mongoose在版本4.2.7中创建了一个新的单个子文档功能(documentation和feature request),允许使用单个嵌入式子文档架构,其行为方式与一对多子文档的行为相同。 在父级
Mongoose 版本 >= 4.0 有一个时间戳选项,当 timestamps 设置为 时,该选项会为架构创建 updatedAt 和 createdAt 字段正确。 http://mongoose
我注意到某些图书馆喜欢 mock 鹅 ( https://github.com/mccormicka/Mockgoose/blob/master/test/index.spec.js ) 使用 req
我正在与 Mongoose 合作。我见过很多开发者发出以下命令: mongoose.Promise = global.Promise; 然后我很好奇 mongoose.Promise 的原始值是什么。
当我运行与数据库大量连接和断开连接的测试时,我收到以下警告。 (node) warning: possible EventEmitter memory leak detected. 11 connec
我可以在 Mongoose 的子文档数组中填充动态引用(使用“refPath”)虚拟字段吗? 数据结构如下 Group - Members -> User 代码:模型/模式 let MemberSc
我正在我的应用程序中做一些测试,看看内存缓存是否真的在工作。但是,由于 memory-cache 显然没有公开“命中”事件,我无法判断是否真的从缓存中获取数据。所以我试着看看当应用程序实际从数据库中获
我是 nestjs 的新手。我使用 @nestjs/mongoose,我需要在我的类模式中引用嵌套对象中的几个字段,但我不知道该怎么做。 dietDays 对象必须包含一个日期字段和包含对 Meal
我是 mongodb 的新手,我有一个这样的数据模型 { last_updated: Date.now(), csgo_items:[ {name: 'name', p
这是我的方案: var documentSchema = mongoose.Schema({ 'facts': [{ 'type': { type: String, requi
我想删除多个 _ids = ['123', '234', '345']; _ids.forEach(_id => { await model.deleteOne({ _id }); }); 有没有
我有一个像这样的 Mongoose 模式: var Address = { doorNo:String, city:String, state:String, coun
我的文档包含一个名为 clients 的字段那应该包含一组客户端ID。 { "first_name":"Nick", "last_name":"Parsons", "email":"nic
我遇到了以下我无法理解的代码行,尽管有很多教程提供了与 populate 的示例相关的信息。但没有一个能解释它究竟意味着什么。这是一个例子 var mongoose = require('mongoo
我有一个具有多个唯一性的架构,如下所示: var userSchema = new mongoose.Schema({ user: { type: String, unique:
我有一个 Mongoose 模式,其中有 4 个子模式。我一直在关注这里的文档https://github.com/LearnBoost/mongoose关于嵌入文档 var scenarios =
我希望每个字符串属性都默认设置为 true。有办法吗? ?? mongoose.Schema.String -> default { trim: true } var schema = new Sch
我有这个代码 var ClientSchema = new Schema({ name: {type: String, required: true, trim: true} }); var Cl
许多教程告诉您在您的 userSchema 页面中使用 bycrypt。保存新用户后,它会附带加密密码。伟大的。然而,我想,当我用某些东西编辑用户时,它也会重新哈希密码,导致无法登录。你能给我一个解决
我是一名优秀的程序员,十分优秀!