Docs Menu
Docs Home
/
Database Manual
/ / / / / /

Query a Document with Encrypted Fields

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.

Create an encrypted collection and insert documents before continuing.

1

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:

const findResult = await encryptedCollection.findOne({
"patientRecord.ssn": "987-65-4320",
});
console.log(findResult);
var ssnFilter = Builders<Patient>.Filter.Eq("patientRecord.ssn", patient.PatientRecord.Ssn);
var findResult = await encryptedCollection.Find(ssnFilter).ToCursorAsync();
Console.WriteLine(findResult.FirstOrDefault().ToJson());
var findResult PatientDocument
err = coll.FindOne(
context.TODO(),
bson.M{"patientRecord.ssn": "987-65-4320"},
).Decode(&findResult)
Patient findResult = collection.find(
new BsonDocument()
.append("patientRecord.ssn", new BsonString("987-65-4320")))
.first();
System.out.println(findResult);
const findResult = await encryptedCollection.findOne({
"patientRecord.ssn": "987-65-4320",
});
console.log(findResult);
$findResult = $encryptedCollection->findOne([
'patientRecord.ssn' => '987-65-4320',
]);
print_r($findResult);
find_result = encrypted_collection.find_one({
"patientRecord.ssn": "987-65-4320"
})
print(find_result)
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

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:

const findResult = await encryptedCollection.findOne({
"patientRecord.billAmount": { $gt: 1000, $lt: 2000 },
});
console.log(findResult);
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());
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)
}
Document filter = new Document("patientRecord.billAmount",
new Document("$gt", 1000).append("$lt", 2000));
Patient findResult = collection.find(filter).first();
System.out.println(findResult);
const findResult = await encryptedCollection.findOne({
"patientRecord.billAmount": { $gt: 1000, $lt: 2000 },
});
console.log(findResult);
$findResult = $encryptedCollection->findOne([
'patientRecord.billAmount' => ['$gt' => 1000, '$lt' => 2000],
]);
print_r($findResult);
query = {"patientRecord.billAmount": {"$gt": 1000, "$lt": 2000}}
find_result = encrypted_collection.find_one(query)
print(find_result)
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

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:

var filter = new BsonDocument("$expr", new BsonDocument("$encStrStartsWith",
new BsonDocument
{
{ "input", "$patientRecord.ssn" },
{ "prefix", "987" }
}));
var findResult = await encryptedCollection.Find(filter).ToCursorAsync();
Console.WriteLine(findResult.FirstOrDefault().ToJson());

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:

var filter = new BsonDocument("$expr", new BsonDocument("$encStrContains",
new BsonDocument
{
{ "input", "$patientRecord.ssn" },
{ "substring", "-65-432" }
}));
var findResult = await encryptedCollection.Find(filter).ToCursorAsync();
Console.WriteLine(findResult.FirstOrDefault().ToJson());
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:

Document filter = new Document("$expr",
new Document("$encStrContains",
new Document()
.append("input", "$patientRecord.ssn")
.append("substring", "-65-432")));
Patient findResult = collection.find(filter).first();
System.out.println(findResult);
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:

const findResult = await encryptedCollection.findOne(
{ $expr: { $encStrContains:
{ input: "$patientRecord.ssn", substring: "-65-432" }
}
})
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:

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

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

{
"_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.

Back

Create a Collection

On this page