MongoDB查询IP字段为null时返回无关文档的问题求助
{"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
IPfield doesn't exist at all - Documents where the
IPfield exists but has a value ofnull
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

