How to Check if a Field Exists in MongoDB

Tahseen Tauseef Feb 02, 2024
  1. Fields in Databases
  2. Fields in MongoDB
  3. Check if Field Exists in MongoDB
  4. Check if Field Exists in a Collection in MongoDB
  5. Check if Embedded Field Exists in MongoDB
  6. When a Field Does Not Exist in MongoDB
How to Check if a Field Exists in MongoDB

This instructional article will tell you all about fields in the database and how you can check whether they exist or not. Moreover, you will get to know how to check embedded fields if they exist inside the database.

Fields in Databases

A field is a physical structure that holds data in a form, file, or database. There are one or more bytes in a field.

A data record comprises ORDER #, NAME, ADDRESS, CITY, etc. The words “search field” and “search-box” are frequently used interchangeably on a Web page.

For database searches, the field is the common denominator. For example, when a database query is run to locate “all customers who live in a country”, the STATE column is used.

The ORDER AMOUNT field is totaled when summing up transactions. When looking for specific employees, JOB TITLE is used.

Fields in MongoDB

In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field.

Check if Field Exists in MongoDB

The $exists operator in MongoDB may be used to verify if a field exists in a given collection. When the $exists operator’s value is set to true, it matches the document that includes the supplied field (including the documents where the value of that field is null).

When the $exists operator’s value is false, this operator only returns documents that don’t include the given field.

Syntax:

{ field: { $exists: <boolean> } }

When <boolean> is true, $exists matches the documents that contain the field, including documents where the field value is null. If <boolean> is false, the query returns only the documents that do not contain the field.

MongoDB $exists does not correspond to SQL operator exists. For SQL exists, $in operator is used.

The $in operator finds documents where a field’s value equals any value in the provided array. Use the following prototype to provide an $in expression.

{ field: { $in: [<value1>, <value2>, ... <valueN> ] } }

In MongoDB, you can use the following methods to see if a field exists in a collection.

Check if Field Exists in a Collection in MongoDB

db.data.find({ "myField": { $exists: true } })

This method determines whether myField exists in the data collection. If it does, all documents containing the field name are returned. It returns nothing if it doesn’t.

Example:

db={
  "data": [
    {
      "_id": ObjectId("611a99100a3322fc1bd8c38b"),
      "fname": "Tom",
      "city": "United States of America",
      "StudentHobby": [
        "c#",
        "asp",
        "gaming"
      ]
    },
    {
      "_id": ObjectId("611a99340a3322fc1bd8c38c"),
      "fname": "Harry",
      "city": "Canada",
      "courses": [
        "python",
        "asp",
        "node"
      ]
    },
    {
      "_id": ObjectId("611a99510a3322fc1bd8c38d"),
      "fname": "Mikky",
      "city": "New Zealand",
      "courses": [
        "python",
        "asp",
        "c++"
      ]
    },
    {
      "_id": ObjectId("611b3e88a60b5002406571c3"),
      "fname": "Ron",
      "city": "United Kingdom",
      "courses": [
        "python",
        "django",
        "node"
      ]
    }
  ]
}

The database configuration is given above; the query to check if the field StudentHobby exists or not is:

db.data.find({ 'StudentHobby' : { '$exists' : true }})

This link is attached for the above query. You can access the execution and play with the code as you want.

The result for this query is shown in the screenshot below.

Field Exists

Check if Embedded Field Exists in MongoDB

db.data.find({ "myField.embeddedField": { $exists: true } })

This method determines if the field embeddedField within the field myField exists in the data collection.

If it does, all documents containing the field name are returned. It returns nothing if it doesn’t.

Database Configuration for query above below is:

db.teams.insertOne({team: "Mavs", class: {conf:"Western", div:"A"}, points: 31})
db.teams.insertOne({team: "Spurs", class: {conf:"Western", div:"A"}, points: 22})
db.teams.insertOne({team: "Jazz", class: {conf:"Western", div:"B"}, points: 19})
db.teams.insertOne({team: "Celtics", class: {conf:"Eastern", div:"C"}, points: 26})

The code below will show whether the embedded field name div exists within the field class in the teams collection.

db.teams.find({ "class.div": { $exists: true } })

The result for this query is shown in the screenshot below.

Field Exists 2

Since the embedded field name div exists in the class field, every document that contains the div embedded field is returned.

When a Field Does Not Exist in MongoDB

db={
  "data": [
    {
      "_id": ObjectId("611a99100a3322fc1bd8c38b"),
      "fname": "Tom",
      "city": "United States of America",
      "StudentHobby": [
        "c#",
        "asp",
        "gaming"
      ]
    },
    {
      "_id": ObjectId("611a99340a3322fc1bd8c38c"),
      "fname": "Harry",
      "city": "Canada",
      "courses": [
        "python",
        "asp",
        "node"
      ]
    },
    {
      "_id": ObjectId("611a99510a3322fc1bd8c38d"),
      "fname": "Mikky",
      "city": "New Zealand",
      "courses": [
        "python",
        "asp",
        "c++"
      ]
    },
    {
      "_id": ObjectId("611b3e88a60b5002406571c3"),
      "fname": "Ron",
      "city": "United Kingdom",
      "courses": [
        "python",
        "django",
        "node"
      ]
    }
  ]
}

You will not get anything if the field does not exist.

db.data.find({ 'StudentTechnicalSubject' : { '$exists' : true }})

Access this link to see working as StudentTechnicalSubject does not exist. The following result will be shown.

no document found

Any database management system’s querying feature is critical for obtaining data. Because large-scale businesses’ databases include complex data types, they prefer to use queries to promptly access their required data.

The operators are the essential part of every query; MongoDB’s $exists operator was practiced in this tutorial. You may use this operator to verify the available fields in documents and obtain the papers that don’t include the requested field.

The $exists operator’s functionality mentioned above is backed by a “Boolean-value” that may be passed.

Related Article - MongoDB Field