$exists - Amazon DocumentDB
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

$exists

$exists运算符用于检查文档中是否存在字段。 $exists在 Amazon DocumentDB 中处理稀疏索引时特别有用,因为索引字段可能不会出现在所有文档中。

要使用您在查询中创建的稀疏索引,必须在涵盖索引的字段中使用 $exists 子句。如果省略$exists,Amazon DocumentDB 将不会使用稀疏索引进行查询。

参数

  • field:要检查是否存在的字段名称。

  • value:一个布尔值(truefalse),用于指定匹配文档中该字段是否应存在 (truefalse) 还是不存在 ()。

示例(MongoDB 外壳)

以下示例演示了如何在food集合中的special_diets字段上使用带有稀疏索引的$exists运算符。

创建示例文档

db.food.insertMany([ { _id: 1, name: "Apple", special_diets: ["vegetarian", "gluten-free"] }, { _id: 2, name: "Broccoli" }, { _id: 3, name: "Chicken", special_diets: ["dairy-free"] } ]);

在 “special_diets” 字段上创建稀疏索引

db.food.createIndex({ "special_diets": 1 }, { sparse: true, name: "special_diets_sparse_asc" });

查询示例

db.food.find({ "special_diets": { $exists: true } });

输出

[ { "_id" : 1, "name" : "Apple", "special_diets" : [ "vegetarian", "gluten-free" ] }, { "_id" : 3, "name" : "Chicken", "special_diets" : [ "dairy-free" ] } ]

代码示例

要查看使用该$exists命令的代码示例,请选择要使用的语言的选项卡:

Node.js
const { MongoClient } = require('mongodb'); async function main() { const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'); const db = client.db('test'); const collection = db.collection('food'); const result = await collection.find({ "special_diets": { $exists: true } }).toArray(); console.log(result); await client.close(); } main();
Python
import pymongo client = pymongo.MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false') db = client['test'] collection = db['food'] result = list(collection.find({"special_diets": {"$exists": True}})) print(result) client.close()