MongoDB - MongoDB CRUD Operations, Query Documents, Query for Null or Missing Fields

Different query operators in MongoDB treat null values differently.

The examples on this page use the db.collection.find() method in the mongo shell. To populate the users collection referenced in the examples, run the following in mongo shell:

db.users.insert(
   [
      { "_id" : 900, "name" : null },
      { "_id" : 901 }
   ]
)

 

Equality Filter

The { name : null } query matches documents that either contain the name field whose value is null or that do not contain the name field.

Given the following query:

db.users.find( { name: null } )

The query returns both documents:

{ "_id" : 900, "name" : null }
{ "_id" : 901 }

If the query uses an index that is sparse, however, then the query will only match null values, not missing fields.

Changed in version 2.6: If using the sparse index results in an incomplete result, MongoDB will not use the index unless a hint() explicitly specifies the index. See Sparse Indexes for more information.

 

Type Check

The { name : { $type: 10 } } query matches documents that contains the name field whose value is null only; i.e. the value of the item field is of BSON Type Null (i.e. 10) :

db.users.find( { name : { $type: 10 } } )

The query returns only the document where the item field has a null value:

{ "_id" : 900, "name" : null }

 

Existence Check

The { name : { $exists: false } } query matches documents that do not contain the item field:

db.users.find( { name : { $exists: false } } )

The query returns only the document that does not contain the item field:

{ "_id" : 901 }

SEE ALSO: The reference documentation for the $type and $exists operators.

 

转载于:https://www.cnblogs.com/huey/p/6120495.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值