簡體   English   中英

Mongoose 如何編寫帶有 if 條件的查詢?

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

假設我有以下查詢:

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存在並具有價值,然后只在查詢中添加相關的匹配子句(僅過去 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);
    });

};

據我了解,我可以建議您遵循一般查詢。 根據您的需要修改它。

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

概括:

  • 使用匹配來過濾結果。
  • 我們正在使用聚合管道,因此您可以在管道中添加更多聚合運算符
  • 使用$and執行邏輯 AND 因為我們想在給定范圍內獲取一些文檔,比如 1 天、2 天或 1 個月(根據您的要求更改日期參數)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM