Mongodb-mongodb CRUD Operations, query Documents, query for Null or Missing fields

Source: Internet
Author: User

Different query operators in MongoDB treat null values differently.

The examples on this page with 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":, "name": null},      {"_id": 901}   ])

Equality Filter

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

Given the following query:

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

The query returns both documents:

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

If the query uses an index of sparse, however, then the query would only match null values, not missing field S.

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

Type Check

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

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

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

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

Existence Check

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

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

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

{"_id": 901}

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

Mongodb-mongodb CRUD Operations, query Documents, query for Null or Missing fields

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.