文档菜单
文档首页
/
MongoDB 手册
/ / / / / /

查询具有加密字段的文档

本页内容

  • 概述
  • 开始前
  • 步骤
  • 使用等式查询加密字段
  • 使用范围查询加密字段

本指南展示了如何使用可查询加密功能的应用程序检索具有加密字段的文档。

完成本指南中的步骤后,您应能够使用应用程序查询加密字段中的数据,并作为授权用户解密这些字段。

在继续之前,请创建一个加密集合并插入文档

1

如果您在加密字段上启用了等式查询,则可以检索具有该字段指定值的文档。

以下示例在加密字段上执行等式查询并打印解密数据

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);
find_result = encrypted_collection.find_one({
"patientRecord.ssn": "987-65-4320"
})
print(find_result)
2

如果您已在加密字段上启用了范围查询,您可以检索该字段的值在您指定的范围内文档。

以下示例在加密字段上执行范围查询并打印解密数据

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);
query = {"patientRecord.billAmount": {"$gt": 1000, "$lt": 2000}}
find_result = encrypted_collection.find_one(query)
print(find_result)

前面代码示例的输出应类似于以下内容

{
"_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"
}
}
]
}

警告

不要修改 __safeContent__ 字段

__safeContent__ 字段对于可查询加密至关重要。不要修改此字段的 内容。

返回

创建集合