首页 > 解决方案 > MongoDB如何添加条件$match条件

问题描述

我有以下架构

{
   f1: "test",
   f2: "something",
   type: "A",
   date: "2018-11-01T00:00:00.000Z",
   deleted: false
},
{
   "f1": "check",
   type: "B",
   deleted: false
}

现在我想要的是获取所有数据,如果type = "A", then add an extra condition to my match query, suppose compare its date with current date. 我目前的查询是:

db.getCollection('myCollection').aggregate([
  {$match:{
        {"deleted":false},
        // I want to check if type is A then compare its date 
  }}
])

标签: mongodbmongooseaggregation-framework

解决方案


您可以尝试$or并说“如果它不是类型 A日期是 x”:

{$match:{
  $and: [
    {deleted: false},
    $or: [
      {type: {$ne: 'A'}},
      {date: {$gte: ISODate("2018-01-01T00:00:00.0Z"), $lt: ISODate("2018-06-01T00:00:00.0Z")}}
    ]
  ]
}}

推荐阅读