ChatGPT解决这个技术问题 Extra ChatGPT

使用 MongoDB 检查字段是否存在

所以我试图找到所有具有字段集且不为空的记录。

我尝试使用 $exists,但是根据 MongoDB documentation,,此查询将返回等于 null 的字段。

$exists 确实匹配包含存储空值的字段的文档。

所以我现在假设我必须做这样的事情:

db.collection.find({ "fieldToCheck" : { $exists : true, $not : null } })

但是,每当我尝试此操作时,我都会收到错误 [invalid use of $not] 有人知道如何查询这个吗?


S
Sergio Tulentsev

使用 $ne(表示“不等于”)

db.collection.find({ "fieldToCheck": { $ne: null } })

这会返回什么?一个空集合?单品?数组?
@iLoveUnicorns:find 始终返回的内容:记录的集合,符合条件。
@SergioTulentsev AFAIK 它返回一个游标
@fernandohur:是的,但是如果您的文件少于一页,您甚至不会看到差异。而且,如果您要从外部驱动程序运行此查询,我很确定它们中的大多数都会保护您免受游标实现细节的影响。
我知道这是旧的,但这是公认的答案:{$exists: true} 是多余的,只需 {$ne: null} 就足够了。
d
deadshot

假设我们有一个如下的集合:

{ 
  "_id":"1234"
  "open":"Yes"
  "things":{
             "paper":1234
             "bottle":"Available"
             "bottle_count":40
            } 
}

我们想知道瓶子字段是否存在?

答:

db.products.find({"things.bottle":{"$exists":true}})

When <boolean> is true, $exists matches the documents that contain the field, including documents where the field value is null. From the docs.
是的,但我不明白为什么数据库会包含 null 值,这很草率
Y
Yakir Manor

我发现这对我有用

db.getCollection('collectionName').findOne({"fieldName" : {$ne: null}})

H
Hardik Gajjar
db.<COLLECTION NAME>.find({ "<FIELD NAME>": { $exists: true, $ne: null } })

D
Dror

本注释写于 2021 年,适用于 MongoDB 5.X 及更早版本。

如果您重视查询性能,则永远不要使用 $exists(或仅在查询的字段上有稀疏索引时才使用它。稀疏索引应与查询的条件匹配,这意味着,如果搜索 $exists:true,则稀疏索引索引应该在 field:{$exist:true} 上,如果你正在查询 $exists:true 稀疏索引应该在 field:{$exist:false} 上

而是使用:

db.collection.find({ "fieldToCheck": {  $ne: null } })

或者

db.collection.find({ "fieldToCheck": {  $eq: null } })

这将要求您在集合的每个文档中包含 fieldToCheck,但是 - 性能将大大提高。


请参阅我的答案:stackoverflow.com/a/72843232/1301837。它解释了 $exists 具有完整索引的当前限制及其原因。
a
arpit1714

我尝试将其转换为布尔条件,如果具有表名的文档已经存在,那么它将附加到同一个文档中,否则它将创建一个。

table_name 是我试图用来查找文档的变量

query = { table_name : {"$exists": "True"}}
    
    result = collection.find(query)
    flag = 0
    for doc in result:
        collection.update_one({}, { "$push" : { table_name : {'name':'hello'} } } )
        flag = 1
    if (flag == 0):
        collection.insert_one({ table_name : {'roll no' : '20'}})

R
Rafiq

聚合示例

https://mongoplayground.net/p/edbKil4Zvwc

db.collection.aggregate([
  {
    "$match": {
      "finishedAt": {
        "$exists": true
      }
    }
  },
  {
    "$unwind": "$tags"
  },
  {
    "$match": {
      "$or": [
        {
          "tags.name": "Singapore"
        },
        {
          "tags.name": "ABC"
        }
      ]
    }
  },
  {
    "$group": {
      "_id": null,
      "count": {
        "$sum": 1
      }
    }
  }
])