你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
聚合管道中的 $unset 阶段用于移除文档中的指定字段。 当需要从聚合查询结果中排除某些字段时(出于隐私、减少有效负载大小或直接清理输出之类的原因),这尤其有用。
语法
$unset 阶段的语法非常简单。 它接受单个参数,该参数可以是字段名称或要从文档中移除的字段名称数组。
{
$unset: "<field1>" | ["<field1>", "<field2>", ...]
}
参数
DESCRIPTION | |
---|---|
field1, field2, ... |
要从文档中移除的字段的名称。 |
示例
下面是一些示例,演示如何在聚合管道中使用 $unset 阶段。
示例 1:移除单个字段
假设要从文档中移除位置字段。
db.stores.aggregate([
{
$unset: "store.location"
}
])
示例输出
[
{
"_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
"store": {
"name": "Downtown Store",
"sales": {
"totalSales": 15000,
"salesByCategory": [
{
"category": "Electronics",
"totalSales": 5000
},
{
"category": "Clothing",
"totalSales": 10000
}
]
}
}
}
]
示例 2:移除多个字段
假设要从文档中移除位置和 sales.totalSales 字段。
db.stores.aggregate([
{
$unset: ["store.location", "store.sales.totalSales"]
}
])
示例输出
[
{
"_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
"store": {
"name": "Downtown Store",
"sales": {
"salesByCategory": [
{
"category": "Electronics",
"totalSales": 5000
},
{
"category": "Clothing",
"totalSales": 10000
}
]
}
}
}
]
示例 3:移除嵌套字段
假设要从文档中移除 staff.totalStaff.fullTime 和 promotionEvents.discounts 字段。
db.stores.aggregate([
{
$unset: ["store.staff.totalStaff.fullTime", "store.promotionEvents.discounts"]
}
])
示例输出
[
{
"_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
"store": {
"name": "Downtown Store",
"staff": {
"totalStaff": {
"partTime": 8
}
},
"promotionEvents": ["Summer Sale", "Black Friday", "Holiday Deals"]
}
}
]
相关内容
- 查看从 MongoDB 迁移到 Azure Cosmos DB for MongoDB (vCore) 的选项
- 通过创建帐户开始。