如果匹配条件不满足,如何将此mongo查询更改为返回零

时间:2018-07-23 19:23:01

标签: mongodb nosql mongodb-query aggregation-framework

考虑我有这个mongo查询:

db.Employee.aggregate(
       [
       { $match: {Date:  { $gte : new ISODate("2018-07-23T00:07:30.767Z") }}},
          {
             $project: {
                info:{$subtract:[{ "$size":{  "$NewBalance"} }, { "$size": {"$OldBalance"}} ] },
         }
      },
   {"$match": {info:{$ne:0}}},
             {"$count":"infoCount"},
             {"$project":{"infoCount":"$infoCount","category":"Employee"}}


   ]
)

在每种情况下,此查询都应投影infoCount和category,但现在是因为在某些情况下,与{info:{$ ne:0}}不匹配,因此如果此匹配满足我就不会返回任何内容:

{ 
    "infoCount" : NumberInt(17), 
    "category" : "Employee"
}

我想如果没有与{info:{$ ne:0}}匹配的东西以这种方式返回:

   { 
        "infoCount" : NumberInt(0), 
        "category" : "Employee"
    }

** NewBalance和OldBalance都是数组。

编辑: 我的收藏是这样的:

{ 
    "_id" : ObjectId("5b56bb2af2ea13c90c8a0809"),  

    "Date" : ISODate("2018-07-24T05:37:46.326+0000"), 
    "OldBalance" : [
        {
            "Date" : ISODate("2018-07-24T05:37:45.951+0000"), 
            "Balance" : "500"
        }, 
        {
            "Date" : ISODate("2018-07-24T05:53:00.071+0000"), 
            "Balance" : "200"
        }
    ], 
        "NewBalance" : [
        {
            "Date" : ISODate("2018-07-24T05:37:45.951+0000"), 
            "Balance" : "500"
        }, 
        {
            "Date" : ISODate("2018-07-24T05:53:00.071+0000"), 
            "Balance" : "200"
        },
                {
            "Date" : ISODate("2018-07-24T05:53:00.071+0000"), 
            "Balance" : "200"
        }
    ]
}

在这种情况下,我希望:

{ 
    "infoCount" : NumberInt(1), 
    "category" : "Employee"
}

如果这两个数组的长度相等,我应该返回:

{ 
    "infoCount" : NumberInt(0), 
    "category" : "Employee"
}

0 个答案:

没有答案