Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: Check if value is null or the array is empty

I would like to match all documents that don't contain the "Company" attribute or where the "Company" value is null or an empty array.

User.find({Company: {$in: [null, [] ]}}, function (err, users) {
      if (err) { throw err; }
      console.log(users.length);

}).then(function(doc) {
      console.log("finish User Company");
});
like image 992
Gelso77 Avatar asked Jul 17 '18 11:07

Gelso77


People also ask

How do you check if an array is not empty in MongoDB?

To find mongo records where an array field exists and not empty, you need to use element query operator $exists to check if array field exists and comparison query operator $ne that matches all values which are not equal to specified value (empty array).

How check key is null in MongoDB?

MongoDB fetch documents containing 'null' If we want to fetch documents from the collection "testtable" which contains the value of "interest" is null, the following mongodb command can be used : >db. testtable. find( { "interest" : null } ).

How do I check if an element is an array in MongoDB?

To search the array of object in MongoDB, you can use $elemMatch operator. This operator allows us to search for more than one component from an array object.


1 Answers

You could use the $or query operator with a check for each condition:

{
  $or: [{
    // Check about no Company key
    Company: {
       $exists: false
    }
  }, {
    // Check for null
    Company: null
  }, {
    // Check for empty array
    Company: {
       $size: 0
    }
  }]
}
like image 120
Orelsanpls Avatar answered Oct 12 '22 10:10

Orelsanpls