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

痞子三分冷 提交于 2021-02-10 13:09:29

问题


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

回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/51379744/mongodb-check-if-value-is-null-or-the-array-is-empty

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!