Gelso77
Gelso77

Reputation: 1895

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");
});

Upvotes: 11

Views: 20547

Answers (3)

Khanna111
Khanna111

Reputation: 3913

You can use the following

db.test.find({
  "Company.0": {
      $exists: false
  }
})

It will take care of (all the conditions that you asked for):

  1. Company:[]
  2. Company: null
  3. Company attribute missing.

It will not care of:

  1. Company:[null,]

Note, here the 0th index is present though it is null.

Upvotes: 4

ppylla
ppylla

Reputation: 1

to display null or missing values in the array, use $map and $cond

  {$map:   { 
      input: {$cond: [ {$eq:[ "$field1.field2.value", [] ] }, [], "$field1"]}, 
      as: "check55", 
      in: "$$check55.field2.value"
   }},

Hope this helps---pradeep

Upvotes: 0

Orelsanpls
Orelsanpls

Reputation: 23515

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

Upvotes: 15

Related Questions