mongodb中存在($exists)空(null)空串("")的判断

// 构造测试数据
db.col00.insertMany([
	{"name": "doc01 text是正常值", "text": "XXXX"},
	{"name": "doc01 text是空串", "text": ""},
	{"name": "doc02 text为null", "text": null},
	{"name": "doc03 text不存在"}
])

// 查询属性text “不存在” 或者 “等于null”的文档
db.col00.find({
    "text": null
})

db.col00.find({
    "text": {
        "$eq": null
    }
})

// 查询属性text “存在” 或者 “不为null”的文档
db.col00.find({
    "text": {
        "$ne": null
    }
})

// 查询属性text“不存在” 或者 “等于null” 或者 “等于空串” 的文档
db.col00.find({
    "$or": [
        {
            "text": null
        },
        {
            "text": ""
        }
    ]
})

// 查询属性text“存在”的文档
db.col00.find({
    "text": {
        "$exists": true
    }
})

// 查询属性text“不存在”的文档
db.col00.find({
    "text": {
        "$exists": false
    }
})

// 总结:“null”包含“不存在”和“等于null”俩个概念
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐