MongoDB 查询:匹配某个字段是否为 null 或是否存在

1. 用法(Usages)

db.collectionNamedb.getCollection('collectionName') 都表示指定某个 Collection

1.1 匹配某个字段是否存在

// 仅查询某个字段查询存在的记录
db.collectionName.find({"field name":{$exists:true}});

// 仅查询某个字段查询不存在的记录
db.collectionName.find({"field name":{$exists:false}});

1.2 匹配某个字段为 null

// 仅查询某个字段为空的记录
// 既然为 null 那么就表示该字段一定存在
db.collectionName.find({"field name":{$exists: true, $eq: null}})
  • 需要注意与 1.4 过滤某个字段为 null 或不存在 的区别;
  • Mongo 中,为 null 的数据必存在;

1.3 匹配某个字段不为 null 且存在

// 仅查询某个字段为不为空且存在的记录
db.collectionName.find({"field name":{$ne:null}});

【注】其实就是 1.4 过滤某个字段为 null 或不存在 的取反。

1.4 匹配某个字段为 null 或不存在

会把字段 不存在 和 字段为 null 的数据都匹配到。

db.collectionName.find({"field name":null});

// 与上面语句一样的效果
db.collectionName.find({"field name":{$eq:null}});

2. 示例(Examples)

插入测试数据:

db.getCollection("null_demo").insert( {
    name: "张三",
    gender: 0,
    address: "上海市"
} );

db.getCollection("null_demo").insert( {
    name: "李四",
    gender: 0 
    // 没有 address 字段
} );

db.getCollection("null_demo").insert( {
    name: "王五",
    gender: 0,
    address: null // address 字段为 null
} );

查询插入的测试数据:

db.null_demo.find()

查询结果:

_idnamegenderaddress
64681d503902000019003aa2张三0上海市
64681e003902000019003aa3李四0(N/A)
64681e1d3902000019003aa4王五0(Null)

【注】N/A:不适用的(Not Applicable)。

2.1 匹配 address 字段是否存在

// 仅查询某个字段查询存在的记录
db.null_demo.find({"address":{$exists:true}});

输出如下:

_idnamegenderaddress
64681d503902000019003aa2张三0上海市
64681e1d3902000019003aa4王五0(Null)
// 仅查询某个字段查询不存在的记录
db.null_demo.find({"address":{$exists:false}});

输出如下:

_idnamegender
64681e003902000019003aa3李四0

2.2 匹配 address 字段为 null

// 仅查询某个字段为空的记录
db.null_demo.find({"address":{$exists: true, $eq: null}})

输出如下:

_idnamegenderaddress
64681e1d3902000019003aa4王五0(Null)

2.3 匹配 address 字段不为 null 且存在

// 仅查询某个字段为不为空且存在的记录
db.null_demo.find({"address":{$ne:null}});

输出如下:

_idnamegenderaddress
64681d503902000019003aa2张三0上海市

2.4 匹配 address 为 null 或 不存在

db.null_demo.find({"address":null});

// 与上面语句一样的效果
db.null_demo.find({"address":{$eq:null}});

输出如下:

_idnamegenderaddress
64681e003902000019003aa3李四0(N/A)
64681e1d3902000019003aa4王五0(Null)

End!

个人博客:Roc’s Blog

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Roc.Chang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值