Mongodb 查询以检查特定字段是否不为空(聚合)

时间:2021-03-17 07:26:35

标签: python django mongodb mongodb-query

我有类似的问题

{
"title": "sjncx",
"desciption": "cknxk jckd",
"price": "29.99",
"stock": "3",
...
}

如果标题 is not empty.(标题存在且不为空),我需要过滤数据。还有 is empty 喜欢 ~ title: "" ~ (所以标题存在但为空)

我尝试了 is not empty

{'title': {'$ne': 'null'}}

我尝试了 is empty

{'title': {'$type': 10}}

那行不通。是什么原因?

2 个答案:

答案 0 :(得分:1)

您可以使用 $in 来涵盖空和空的情况:

{
  "title": {
    "$nin": [null, ""]
  }
}

试试here

答案 1 :(得分:1)

使用 $and 很有表现力

db.collection.find({
  "$and": [
    {
      "title": {
        "$ne": null
      }
    },
    {
      "title": {
        "$ne": ""
      }
    }
  ]
})

您只需在那里设置您的条件即可。 doc

见:https://mongoplayground.net/p/V13mnmf6xGE