> For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

# Query a Document with Encrypted Fields

## Overview

This guide shows you how to use a Queryable Encryption-enabled application to retrieve a document that has encrypted fields.

After you complete the steps in this guide, you should be able to use your application to query data in encrypted fields, and to decrypt those fields as an authorized user.

## Before You Start

[Create an encrypted collection and insert documents](https://www.mongodb.com/docs/manual/core/queryable-encryption/qe-create-encrypted-collection.md#std-label-qe-create-encrypted-collection) before continuing.

## Procedure

1. Query an encrypted field with equality.

   If you enabled equality queries on an encrypted field, you can retrieve documents that have a specified value in that field.

   The following example performs an equality query on an encrypted field and prints the decrypted data:

   ```javascript
   const findResult = await encryptedCollection.findOne({
     "patientRecord.ssn": "987-65-4320",
   });
   console.log(findResult);
   ```

2. Query an encrypted field with range.

   If you enabled range queries on an encrypted field, you can retrieve documents where the value of that field is within the range that you specify.

   The following example performs a range query on an encrypted field and prints the decrypted data:

   ```javascript
   const findResult = await encryptedCollection.findOne({
     "patientRecord.billAmount": { $gt: 1000, $lt: 2000 },
   });
   console.log(findResult);
   ```

3. Query an encrypted field for a prefix, suffix, or substring match.

   **Note:**

   MongoDB Shell does not currently support prefix, suffix, or substring queries on encrypted fields.

1) Query an encrypted field with equality.

   If you enabled equality queries on an encrypted field, you can retrieve documents that have a specified value in that field.

   The following example performs an equality query on an encrypted field and prints the decrypted data:

   ```javascript
   const findResult = await encryptedCollection.findOne({
     "patientRecord.ssn": "987-65-4320",
   });
   console.log(findResult);
   ```

2) Query an encrypted field with range.

   If you enabled range queries on an encrypted field, you can retrieve documents where the value of that field is within the range that you specify.

   The following example performs a range query on an encrypted field and prints the decrypted data:

   ```javascript
   const findResult = await encryptedCollection.findOne({
     "patientRecord.billAmount": { $gt: 1000, $lt: 2000 },
   });
   console.log(findResult);
   ```

3) Query an encrypted field for a prefix, suffix, or substring match.

   If you enabled prefix, suffix, or substring queries on an encrypted field, you can retrieve documents where the value of that field includes the string specified in your search criteria.

   The following example performs a prefix query on an encrypted field and prints the decrypted data:

   ```javascript
   const findResult = await encryptedCollection.findOne(
     { $expr: { $encStrStartsWith: 
       { input: "$patientRecord.ssn", prefix: "987" } 
     } 
   })
   ```

   To perform a suffix query, replace `$encStrStartsWith` with `$encStrEndsWith`. Then, replace the `prefix` option with the `suffix` option.

   To perform a substring query, use the `$encStrContains` operator, as shown in the following example:

   ```javascript
   const findResult = await encryptedCollection.findOne(
     { $expr: { $encStrContains: 
       { input: "$patientRecord.ssn", substring: "-65-4" } 
     } 
   })
   ```

1. Query an encrypted field with equality.

   If you enabled equality queries on an encrypted field, you can retrieve documents that have a specified value in that field.

   The following example performs an equality query on an encrypted field and prints the decrypted data:

   ```python
   find_result = encrypted_collection.find_one({
       "patientRecord.ssn": "987-65-4320"
   })

   print(find_result)
   ```

2. Query an encrypted field with range.

   If you enabled range queries on an encrypted field, you can retrieve documents where the value of that field is within the range that you specify.

   The following example performs a range query on an encrypted field and prints the decrypted data:

   ```python
   query = {"patientRecord.billAmount": {"$gt": 1000, "$lt": 2000}}
   find_result = encrypted_collection.find_one(query)

   print(find_result)
   ```

3. Query an encrypted field for a prefix, suffix, or substring match.

   If you enabled prefix, suffix, or substring queries on an encrypted field, you can retrieve documents where the value of that field includes the string specified in your search criteria.

   The following example performs a prefix query on an encrypted field and prints the decrypted data:

   ```python
   find_result = encrypted_collection.find_one(
      { "$expr": { "$encStrStartsWith": 
         { "input": "$patientRecord.ssn", "prefix": "987" } 
       } 
   })
   ```

   To perform a suffix query, replace `$encStrStartsWith` with `$encStrEndsWith`. Then, replace the `prefix` option with the `suffix` option.

   To perform a substring query, use the `$encStrContains` operator, as shown in the following example:

   ```python
   find_result = encrypted_collection.find_one(
      { "$expr": { "$encStrContains": 
         { "input": "$patientRecord.ssn", "substring": "-65-4" }
       } 
   })
   ```

1) Query an encrypted field with equality.

   If you enabled equality queries on an encrypted field, you can retrieve documents that have a specified value in that field.

   The following example performs an equality query on an encrypted field and prints the decrypted data:

   ```java
   Patient findResult = collection.find(
       new BsonDocument()
               .append("patientRecord.ssn", new BsonString("987-65-4320")))
               .first();
    
   System.out.println(findResult);
   ```

2) Query an encrypted field with range.

   If you enabled range queries on an encrypted field, you can retrieve documents where the value of that field is within the range that you specify.

   The following example performs a range query on an encrypted field and prints the decrypted data:

   ```java
   Document filter = new Document("patientRecord.billAmount",
       new Document("$gt", 1000).append("$lt", 2000));
   Patient findResult = collection.find(filter).first();

   System.out.println(findResult);
   ```

3) Query an encrypted field for a prefix, suffix, or substring match.

   If you enabled prefix, suffix, or substring queries on an encrypted field, you can retrieve documents where the value of that field includes the string specified in your search criteria.

   The following example performs a prefix query on an encrypted field and prints the decrypted data:

   ```java
   Document filter = new Document("$expr", 
       new Document("$encStrStartsWith", 
           new Document()
               .append("input", "$patientRecord.ssn")
               .append("prefix", "987")));
               
   Patient findResult = collection.find(filter).first();

   System.out.println(findResult);
   ```

   To perform a suffix query, replace `$encStrStartsWith` with `$encStrEndsWith`. Then, replace the `prefix` option with the `suffix` option.

   To perform a substring query, use the `$encStrContains` operator, as shown in the following example:

   ```java
   Document filter = new Document("$expr", 
       new Document("$encStrContains", 
           new Document()
               .append("input", "$patientRecord.ssn")
               .append("substring", "-65-4")));
               
   Patient findResult = collection.find(filter).first();

   System.out.println(findResult);
   ```

1. Query an encrypted field with equality.

   If you enabled equality queries on an encrypted field, you can retrieve documents that have a specified value in that field.

   The following example performs an equality query on an encrypted field and prints the decrypted data:

   ```go
   var findResult PatientDocument
   err = coll.FindOne(
   	context.TODO(),
   	bson.M{"patientRecord.ssn": "987-65-4320"},
   ).Decode(&findResult)
   if err != nil {
   	fmt.Print("Unable to find the document\n")
   } else {
   	output, _ := json.MarshalIndent(findResult, "", "    ")
   	fmt.Printf("%s\n", output)
   }
   ```

2. Query an encrypted field with range.

   If you enabled range queries on an encrypted field, you can retrieve documents where the value of that field is within the range that you specify.

   The following example performs a range query on an encrypted field and prints the decrypted data:

   ```go
   filter := bson.D{
   	{"patientRecord.billAmount", bson.D{
   		{"$gt", 1000},
   		{"$lt", 2000},
   	}},
   }
   var findResult PatientDocument
   err = coll.FindOne(context.TODO(), filter).Decode(&findResult)
   if err != nil {
   	log.Fatal(err)
   }

   if err != nil {
   	fmt.Print("Unable to find the document\n")
   } else {
   	output, _ := json.MarshalIndent(findResult, "", "    ")
   	fmt.Printf("%s\n", output)
   }
   ```

3. Query an encrypted field for a prefix, suffix, or substring match.

   If you enabled prefix, suffix, or substring queries on an encrypted field, you can retrieve documents where the value of that field includes the string specified in your search criteria.

   The following example performs a prefix query on an encrypted field and prints the decrypted data:

   ```go
   filter := bson.D{
   	{"$expr", bson.D{
   		{"$encStrStartsWith", bson.D{
   			{"input", "$patientRecord.ssn"},
   			{"prefix", "987"},
   		}},
   	}},
   }
   var findResult PatientDocument
   err = coll.FindOne(context.TODO(), filter).Decode(&findResult)
   if err != nil {
   	log.Fatal(err)
   }

   output, _ := json.MarshalIndent(findResult, "", "    ")
   fmt.Printf("%s\n", output)
   ```

   To perform a suffix query, replace `$encStrStartsWith` with `$encStrEndsWith` in the previous example. Then, replace the `prefix` option with the `suffix` option.

   To perform a substring query, use the `$encStrContains` operator, as shown in the following example:

   ```go
   filter := bson.D{
   	{"$expr", bson.D{
   		{"$encStrContains", bson.D{
   			{"input", "$patientRecord.ssn"},
   			{"substring", "-65-4"},
   		}},
   	}},
   }
   var findResult PatientDocument
   err = coll.FindOne(context.TODO(), filter).Decode(&findResult)
   if err != nil {
   	log.Fatal(err)
   }

   output, _ := json.MarshalIndent(findResult, "", "    ")
   fmt.Printf("%s\n", output)
   ```

1) Query an encrypted field with equality.

   If you enabled equality queries on an encrypted field, you can retrieve documents that have a specified value in that field.

   The following example performs an equality query on an encrypted field and prints the decrypted data:

   ```csharp
   var ssnFilter = Builders<Patient>.Filter.Eq("patientRecord.ssn", patient.PatientRecord.Ssn);
   var findResult = await encryptedCollection.Find(ssnFilter).FirstOrDefaultAsync();

   Console.WriteLine(findResult.ToJson(new JsonWriterSettings { Indent = true }));
   ```

2) Query an encrypted field with range.

   If you enabled range queries on an encrypted field, you can retrieve documents where the value of that field is within the range that you specify.

   The following example performs a range query on an encrypted field and prints the decrypted data:

   ```csharp
   var filter = Builders<Patient>.Filter.Gt("patientRecord.billAmount", 1000) &
                Builders<Patient>.Filter.Lt("patientRecord.billAmount", 2000);

   var findResult = encryptedCollection.Find(filter).FirstOrDefault();
   Console.WriteLine(findResult.ToJson());
   ```

3) Query an encrypted field for a prefix, suffix, or substring match.

   If you enabled prefix, suffix, or substring queries on an encrypted field, you can retrieve documents where the value of that field includes the string specified in your search criteria.

   The following example performs a prefix query on an encrypted field and prints the decrypted data:

   ```csharp
   var filter = Builders<Patient>.Filter.EncStrStartsWith("patientRecord.ssn", "987");

   var findResult = encryptedCollection.Find(filter).FirstOrDefault();
   Console.WriteLine(findResult.ToJson());
   ```

   To perform a suffix query, replace the `EncStrStartsWith()` builder method with the `EncStrEndsWith()` method.

   To perform a substring query, use the `EncStrContains()` builder method, as shown in the following example:

   ```csharp
   var filter = Builders<Patient>.Filter.EncStrContains("patientRecord.ssn", "-65-4");

   var findResult = encryptedCollection.Find(filter).FirstOrDefault();
   Console.WriteLine(findResult.ToJson());
   ```

1. Query an encrypted field with equality.

   If you enabled equality queries on an encrypted field, you can retrieve documents that have a specified value in that field.

   The following example performs an equality query on an encrypted field and prints the decrypted data:

   ```rust
   let find_result = encrypted_coll.find_one(doc! {"patientRecord.ssn": "987-65-4320"}).await?;

   match find_result {
       Some(document) => println!("{:?}", document),
       None => println!("Document not found"),
   }
   ```

2. Query an encrypted field with range.

   If you enabled range queries on an encrypted field, you can retrieve documents where the value of that field is within the range that you specify.

   The following example performs a range query on an encrypted field and prints the decrypted data:

   ```rust
   let query =
       doc! { "$and": [
           doc! { "patientRecord.billAmount": doc! { "$gt": 1000 } },
           doc! { "patientRecord.billAmount": doc! { "$lt": 2000 } }
       ]
   };
   let find_result = encrypted_coll.find_one(query).await?;

   match find_result {
       Some(document) => println!("{:?}", document),
       None => println!("Document not found"),
   }
   ```

3. Query an encrypted field for a prefix, suffix, or substring match.

   If you enabled prefix, suffix, or substring queries on an encrypted field, you can retrieve documents where the value of that field includes the string specified in your search criteria.

   The following example performs a prefix query on an encrypted field and prints the decrypted data:

   ```rust
   let query =
       doc! { "$expr": doc! {
           "$encStrStartsWith": doc! {
               "input": "$patientRecord.ssn",
               "prefix": "987"
           }
       }
   };
   let find_result = encrypted_coll.find_one(query).await?;

   match find_result {
       Some(document) => println!("{:?}", document),
       None => println!("Document not found"),
   }
   ```

   To perform a suffix query, replace `$encStrStartsWith` with `$encStrEndsWith` in the preceding example. Then, replace the `prefix` option with the `suffix` option.

   To perform a substring query, use the `$encStrContains` operator, as shown in the following example:

   ```rust
   let query =
       doc! { "$expr": doc! {
           "$encStrContains": doc! {
               "input": "$patientRecord.ssn",
               "substring": "-65-4"
           }
       }
   };
   let find_result = encrypted_coll.find_one(query).await?;

   match find_result {
       Some(document) => println!("{:?}", document),
       None => println!("Document not found"),
   }
   ```

1) Query an encrypted field with equality.

   If you enabled equality queries on an encrypted field, you can retrieve documents that have a specified value in that field.

   The following example performs an equality query on an encrypted field and prints the decrypted data:

   ```cpp
   auto const find_result = encrypted_collection.find_one(
       make_document(kvp("patientRecord.ssn", "987-65-4320")));

   if (find_result) {
       std::cout << bsoncxx::to_json(*find_result) << std::endl;
   } else {
       std::cout << "Document not found" << std::endl;
   }
   ```

2) Query an encrypted field with range.

   If you enabled range queries on an encrypted field, you can retrieve documents where the value of that field is within the range that you specify.

   The following example performs a range query on an encrypted field and prints the decrypted data:

   ```cpp
   auto const find_result = encrypted_collection.find_one(make_document(kvp("$and", bsoncxx::builder::basic::make_array(
       make_document(kvp("patientRecord.billAmount", make_document(kvp("$gt", 1000)))),
       make_document(kvp("patientRecord.billAmount", make_document(kvp("$lt", 2000))))))));

   if (find_result) {
       std::cout << bsoncxx::to_json(*find_result) << std::endl;
   } else {
       std::cout << "Document not found" << std::endl;
   }
   ```

3) Query an encrypted field for a prefix, suffix, or substring match.

   If you enabled prefix, suffix, or substring queries on an encrypted field, you can retrieve documents where the value of that field includes the string specified in your search criteria.

   The following example performs a prefix query on an encrypted field and prints the decrypted data:

   ```cpp
   auto const find_result = encrypted_collection.find_one(make_document(kvp("$expr", make_document(
       kvp("$encStrStartsWith", make_document(
           kvp("input", "$patientRecord.ssn"),
           kvp("prefix", "987")))))));

   if (find_result) {
       std::cout << bsoncxx::to_json(*find_result) << std::endl;
   } else {
       std::cout << "Document not found" << std::endl;
   }
   ```

   To perform a suffix query, replace `$encStrStartsWith` with `$encStrEndsWith` in the preceding example. Then, replace the `prefix` option with the `suffix` option.

   To perform a substring query, use the `$encStrContains` operator, as shown in the following example:

   ```cpp
   auto const find_result = encrypted_collection.find_one(make_document(kvp("$expr", make_document(
       kvp("$encStrContains", make_document(
           kvp("input", "$patientRecord.ssn"),
           kvp("substring", "-65-4")))))));

   if (find_result) {
       std::cout << bsoncxx::to_json(*find_result) << std::endl;
   } else {
       std::cout << "Document not found" << std::endl;
   }
   ```

1. Query an encrypted field with equality.

   If you enabled equality queries on an encrypted field, you can retrieve documents that have a specified value in that field.

   The following example performs an equality query on an encrypted field and prints the decrypted data:

   ```php
   $findResult = $encryptedCollection->findOne([
       'patientRecord.ssn' => '987-65-4320',
   ]);

   print(json_encode($findResult, JSON_PRETTY_PRINT));
   ```

2. Query an encrypted field with range.

   If you enabled range queries on an encrypted field, you can retrieve documents where the value of that field is within the range that you specify.

   The following example performs a range query on an encrypted field and prints the decrypted data:

   ```php
   $findResult = $encryptedCollection->findOne([
       'patientRecord.billAmount' => ['$gt' => 1000, '$lt' => 2000],
   ]);
   print_r($findResult);
   ```

3. Query an encrypted field for a prefix, suffix, or substring match.

   If you enabled prefix, suffix, or substring queries on an encrypted field, you can retrieve documents where the value of that field includes the string specified in your search criteria.

   The following example performs a prefix query on an encrypted field and prints the decrypted data:

   ```php
   $findResult = $encryptedCollection->findOne([
       '$expr' => [
           '$encStrStartsWith' => [
               'input' => '$patientRecord.ssn',
               'prefix' => '987',
           ],
       ],
   ]);
   print_r($findResult);
   ```

   To perform a suffix query, replace `$encStrStartsWith` with `$encStrEndsWith` in the preceding example. Then, replace the `prefix` option with the `suffix` option.

   To perform a substring query, use the `$encStrContains` operator, as shown in the following example:

   ```php
   $findResult = $encryptedCollection->findOne([
       '$expr' => [
           '$encStrContains' => [
               'input' => '$patientRecord.ssn',
               'substring' => '-65-4',
           ],
       ],
   ]);
   print_r($findResult);
   ```

1) Query an encrypted field with equality.

   If you enabled equality queries on an encrypted field, you can retrieve documents that have a specified value in that field.

   The following example performs an equality query on an encrypted field and prints the decrypted data:

   ```ruby
   find_result = encrypted_collection.find("patientRecord.ssn" => "987-65-4320").first
   puts find_result.inspect
   ```

2) Query an encrypted field with range.

   If you enabled range queries on an encrypted field, you can retrieve documents where the value of that field is within the range that you specify.

   The following example performs a range query on an encrypted field and prints the decrypted data:

   ```ruby
   find_result = encrypted_collection.find(
     "patientRecord.billAmount" => { "$gt" => 1000, "$lt" => 2000 }
   ).first
   puts find_result.inspect
   ```

3) Query an encrypted field for a prefix, suffix, or substring match.

   If you enabled prefix, suffix, or substring queries on an encrypted field, you can retrieve documents where the value of that field includes the string specified in your search criteria.

   The following example performs a prefix query on an encrypted field and prints the decrypted data:

   ```ruby
   find_result = encrypted_collection.find(
     "$expr" => {
       "$encStrStartsWith" => {
         "input" => "$patientRecord.ssn",
         "prefix" => "987"
       }
     }
   ).first
   puts find_result.inspect
   ```

   To perform a suffix query, replace `$encStrStartsWith` with `$encStrEndsWith` in the preceding example. Then, replace the `prefix` option with the `suffix` option.

   To perform a substring query, use the `$encStrContains` operator, as shown in the following example:

   ```ruby
   find_result = encrypted_collection.find(
     "$expr" => {
       "$encStrContains" => {
         "input" => "$patientRecord.ssn",
         "substring" => "-65-4"
       }
     }
   ).first
   puts find_result.inspect
   ```

### Query Result

The output of the preceding code examples should look similar to the following:

```json
{
  "_id": {
    "$oid": "648b384a722cb9b8392df76a"
  },
  "name": "Jon Doe",
  "record": {
    "ssn": "987-65-4320",
    "billing": {
      "type": "Visa",
      "number": "4111111111111111"
    },
    "billAmount": 1500
  },
  "__safeContent__": [
    {
      "$binary": {
        "base64": "L1NsYItk0Sg+oL66DBj6IYHbX7tveANQyrU2cvMzD9Y=",
        "subType": "00"
      }
    }
  ]
}

```

**Warning: Do not Modify the \_\_safeContent\_\_ Field**

The `__safeContent__` field is essential to Queryable Encryption. Do not modify the contents of this field.
