【问题标题】:MongoDB how to add conditional $match conditionMongoDB如何添加条件$match条件
【发布时间】:2019-04-04 12:36:03
【问题描述】:

我有以下架构

{
   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 
  }}
])

【问题讨论】:

    标签: mongodb mongoose aggregation-framework


    【解决方案1】:

    您可以尝试$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")}}
        ]
      ]
    }}
    

    【讨论】:

      【解决方案2】:

      使用$match$or 条件。

      db.getCollection('tests').aggregate([
        { $match: {
          $or : [
            { "deleted": false, "type": "A", "date": ISODate("2018-11-01T00:00:00.000Z") },
            { "deleted": false, type: { $ne: "A" }}
          ]}
        }
      ])
      

      【讨论】:

        猜你喜欢
        • 2020-08-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-09
        • 1970-01-01
        • 1970-01-01
        • 2015-06-21
        相关资源
        最近更新 更多