MongoDB-查询Null和Missing字段
时间:2020-02-23 14:40:52 来源:igfitidea点击:
在此MongoDB教程中,我们将学习查询Null和缺少的字段。
登录到您的MongoDB服务器并插入以下文档。
对于本教程,我将文档插入deliveryAddress集合中。
> db.deliveryAddress.insertMany([ { "addressLine1": "House #1, 2nd Street, 1st Main Road", "addressLine2": "Opposite Bakery", "city": "Bangalore", "state": "KA", "country": "India", "pincode": "560001", "contactphone": "919800000000", "contactperson": "John Doe" }, { "addressLine1": "House #20, 3rd Street, 5th Main Road", "addressLine2": null, "city": "Bangalore", "state": "KA", "country": "India", "pincode": "560001", "contactperson": "Jane Doe" }, { "addressLine1": "House #20, 5th Street, 10th Main Road", "addressLine2": null, "city": "Bangalore", "state": "KA", "country": "India", "pincode": "560001", "contactphone": null, "contactperson": "Jim Doe" } ])
选择所有具有空字段的文档
在下面的示例中,我们将提取所有具有" addressLine2"字段设置为" null"值的文档。
> db.deliveryAddress.find({ "addressLine2": null }).pretty() { "_id" : ObjectId("5d76170f89ccf6fae0c7974b"), "addressLine1" : "House #20, 3rd Street, 5th Main Road", "addressLine2" : null, "city" : "Bangalore", "state" : "KA", "country" : "India", "pincode" : "560001", "contactperson" : "Jane Doe" } { "_id" : ObjectId("5d76170f89ccf6fae0c7974c"), "addressLine1" : "House #20, 5th Street, 10th Main Road", "addressLine2" : null, "city" : "Bangalore", "state" : "KA", "country" : "India", "pincode" : "560001", "contactphone" : null, "contactperson" : "Jim Doe" }
$exists运算符
要检查文档是否包含给定字段,我们使用$exists运算符。
语法
我们使用以下语法来获取确实包含给定字段的给定集合的所有文档。
db.collectionName.find({ field: { $exists: true } })
我们使用以下语法来获取不包含给定字段的给定集合的所有文档。
db.collectionName.find({ field: { $exists: false } })
选择所有没有给定字段的文档
在下面的示例中,我们将获取所有没有" contactphone"字段的文档。
> db.deliveryAddress.find({ "contactphone": { $exists: false } }).pretty() { "_id" : ObjectId("5d76170f89ccf6fae0c7974b"), "addressLine1" : "House #20, 3rd Street, 5th Main Road", "addressLine2" : null, "city" : "Bangalore", "state" : "KA", "country" : "India", "pincode" : "560001", "contactperson" : "Jane Doe" }