MongoDB:检查值是否为空或数组是否为空

MongoDB:检查值是否为空或数组是否为空

问题描述:

我想匹配所有不包含公司"属性或公司"值为空或空数组的文档.

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

您可以使用 $or 查询运算符,检查每个条件:

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