本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$$KEEP
$$KEEP 系統變數會與彙總管道中的$redact階段搭配使用,以保持目前文件或欄位不變,並將其包含在輸出中。
參數
無
範例 (MongoDB Shell)
下列範例示範在 Amazon DocumentDB 彙總管道$$KEEP中使用 。只有在存取等於「公開」時才會保留文件,否則會將其移除。
建立範例文件
db.articles.insertMany([
{ title: "Article A", access: "public", content: "Visible content" },
{ title: "Article B", access: "private", content: "Hidden content" }
]);
查詢範例
db.articles.aggregate([
{
$redact: {
$cond: [
{ $eq: ["$access", "public"] },
"$$KEEP",
"$$PRUNE"
]
}
}
]);
輸出
[
{
"_id" : ObjectId("..."),
"title" : "Article A",
"access" : "public",
"content" : "Visible content"
}
]
程式碼範例
若要檢視使用 $$KEEP命令的程式碼範例,請選擇您要使用的語言標籤:
- Node.js
-
const { MongoClient } = require('mongodb');
async function run() {
const client = new MongoClient(
'mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0'
);
try {
await client.connect();
const db = client.db('test');
const articles = db.collection('articles');
const pipeline = [
{
$redact: {
$cond: [
{ $eq: ["$access", "public"] },
"$$KEEP",
"$$PRUNE"
]
}
}
];
const results = await articles.aggregate(pipeline).toArray();
console.log(results);
} finally {
await client.close();
}
}
run().catch(console.error);
- Python
-
from pymongo import MongoClient
client = MongoClient(
"mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0"
)
db = client.test
articles = db.articles
pipeline = [
{
"$redact": {
"$cond": [
{"$eq": ["$access", "public"]},
"$$KEEP",
"$$PRUNE"
]
}
}
]
results = list(articles.aggregate(pipeline))
print(results)
client.close()