简体   繁体   English

Mongoose 如何编写带有 if 条件的查询?

[英]Mongoose how to write a query with if condition?

Suppose I have the following query:假设我有以下查询:

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);
});
};

What i want to do is: 1- check if queryData.dateGroups.thirtyHourAgo existed and has value, then only add the relevant match clause in query (count of posts only for past 30 hour).我想要做的是: 1- 检查queryData.dateGroups.thirtyHourAgo存在并具有价值,然后只在查询中添加相关的匹配子句(仅过去 30 小时的帖子数)。 2- check if queryData.dateGroups.fourtyHourAgo existed, then add relevant query section (count of posts for past 30 hour, and past 48 hour ago). 2- 检查queryData.dateGroups.fourtyHourAgo存在,然后添加相关查询部分(过去 30 小时和过去 ​​48 小时前的帖子数)。 3 and the same for queryData.dateGroups.oneMonthAgo (count of posts for past 30 hour, 48 hour, and past one month). 3 和queryData.dateGroups.oneMonthAgo相同(过去 30 小时、48 小时和过去一个月的帖子数)。

I need something like Mysql if condition to check if a variable existed and not empty then include a query clause.我需要类似 Mysql 的 if 条件来检查变量是否存在且不为空,然后包含一个查询子句。 Is it possible to do that?有可能这样做吗?

My sample data is like:我的样本数据是这样的:

/* 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
}

Suppose I have three link in my application interface: 1- 30 hour ago posts.假设我的应用程序界面中有三个链接:1- 30 小时前的帖子。 2- 48 hour ago posts. 2-48 小时前的帖子。 3- last one month posts. 3- 最近一个月的帖子。

Now if user click on first link i should control to group posts only for 30 hour ago, but if user click on second link, i should prepare my query to group posts for 30 hour and also for 48 hour, and if user click on third link i should prepare for all of them.现在,如果用户点击第一个链接,我应该控制只对 30 小时前的帖子进行分组,但是如果用户点击第二个链接,我应该准备我的查询以将帖子分组 30 小时和 48 小时,如果用户点击第三个链接我应该为所有这些做好准备。

I want something like:我想要这样的东西:

 var pipeline = [
  {
    $match: match
  },
  {
    $group: {
      _id: null,
      if (myVariable) {
        thirtyHourAgo: {
          ........
          ........
        }
      } 
      if (mysecondVariable) {
        fortyEightHourAgo: {
          ........
          ........
        }
      }

You can use javascript to dynamically create json document based on your query parameters.您可以使用 javascript 根据您的查询参数动态创建 json 文档。

Your updated function will look something like您更新后的功能看起来像

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);
    });

};

As I understood, I can suggest you following general query.据我了解,我可以建议您遵循一般查询。 Modify this according to your need.根据您的需要修改它。

db.getCollection('vacancy')
.aggregate([{$match: { $and: [ 
{publishDate:{ $gte: new Date(2017, 4, 13) }} , 
{publishDate:{ $lte: new Date(2017, 4, 14) }}
]} }])

Summary:概括:

  • Used match to filter out result.使用匹配来过滤结果。
  • We are using aggregation Pipeline so you can add more aggregate operators n the pipeline我们正在使用聚合管道,因此您可以在管道中添加更多聚合运算符
  • Using $and perform a logical AND because we want to fetch some documents between a give range say 1 day, 2 days or 1 month (change date parameters according to your requirement)使用$and执行逻辑 AND 因为我们想在给定范围内获取一些文档,比如 1 天、2 天或 1 个月(根据您的要求更改日期参数)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM