You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB查询IP字段为null时返回无关文档的问题求助

解决MongoDB查询{"IP":null}返回无IP字段文档的问题

Ah, I know this gotcha well! In MongoDB, the query {"IP":null} has a behavior that trips up a lot of folks — it matches two distinct types of documents:

  • Documents where the IP field doesn't exist at all
  • Documents where the IP field exists but has a value of null

If you want to only get documents where the IP field exists and its value is null, you have two solid options:

Option 1: Combine $exists and $eq

Use $exists: true to guarantee the field is present, then $eq: null to target the null value specifically:

db.collection.find({
  "IP": {
    "$exists": true,
    "$eq": null
  }
})

Option 2: Use the $type operator

In MongoDB, the BSON type for null is numbered 10. Querying by this type will automatically only include documents where the field exists and is null:

db.collection.find({ "IP": { "$type": 10 } })

As a bonus, if you ever need to query for documents that don't have the IP field at all, you can use:

db.collection.find({ "IP": { "$exists": false } })

That should get you exactly the subset of documents you're looking for!

内容的提问来源于stack exchange,提问作者Vijay Rajpurohit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:30:11