MongoDB aggregate by field exists

前端 未结 6 1458
不思量自难忘°
不思量自难忘° 2020-12-02 12:33

I have a hard time believing this question hasn\'t been asked and answered somewhere already, but I can\'t find any trace of it.

I have a MongoDB aggregation query t

6条回答
  •  感情败类
    2020-12-02 12:57

    The $exists operator is a "query" operator, so it is used basically to "filter" results rather than identify a logical condition.

    As a "logical" operator the aggregation framework supports the $ifNull operator. This returns the field value where it exists or the alternate supplied value where it does not or otherwise evaluates to null

    db.test.aggregate([
        { "$group": {
            "_id": { "$ifNull": [ "$field", false ] },
            "count": { "$sum": 1 }
        }}
    ])
    

    But of course, even that is not a "true/false" comparison, so unless you actually want to return the actual value of the field where it is present, then you are probably better off with a $cond statement much like you have:

    db.test.aggregate([
        { "$group": {
            "_id": { "$cond": [{ "$eq": [ "$field", null ] }, true, false ] },
            "count": { "$sum": 1 }
        }}
    ])
    

    Where $ifNull can be very useful is in replacing not existent array fields that would otherwise cause an error using $unwind. You can then do something like return a single element or empty array so this does not cause problems in the rest of your pipeline processing.

提交回复
热议问题