Home > Blockchain >  MongoDB aggregate match empty array
MongoDB aggregate match empty array

Time:02-04

I have a collection in a MongoDB that contains a field "events" which is an array. I need to write an aggregate query for this that checks for the events array to not be empty, but can't find a way to do this.

I want something like:

db.collection.aggregate([
    { 
        $match: { 
            events: {
                "$empty": false 
            }
        }
    }
]);

CodePudding user response:

After some digging around and having tried several options (including a nasty project of $gte: 0 of the $size followed by a match on that projected field) I eventually found the following makes sense and actually works:

db.collection.aggregate([
    { 
        $match: { 
            "events.0": {
                "$exists": true 
            }
        }
    }
]);

CodePudding user response:

Query

  • match to test if not-equal with the empty array

Test code here

*this query looks straight forward way to do it(yours looks more tricky), but i dont know which is faster, if you benchmark it or anyone knows add on comments if you can

aggregate([{"$match":{"$expr":{"$ne":["$events", []]}}}])
  •  Tags:  
  • Related