$documents
聚合管道阶段用于从一组提供的文档创建管道。 如果要在不查询集合的情况下处理特定文档,此阶段特别有用。
语法
{
$documents: [
<document1>,
<document2>,
...
]
}
参数
参数 | DESCRIPTION |
---|---|
<document> |
表示要在管道中包含的文档的 JSON 对象。 |
例子
示例 1:从特定文档创建管道
以下示例演示如何使用 $documents
阶段来处理一组预定义文档:
db.aggregate([
{
$documents: [
{
"_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
"name": "Lakeshore Retail | Holiday Supply Hub - Marvinfort",
"location": {
"lat": 60.1441,
"lon": -141.5012
},
"sales": {
"fullSales": 3700
},
"tag": ["#ShopLocal", "#SeasonalSale"]
},
{
"_id": "7e53ca0f-6e24-4177-966c-fe62a11e9af5",
"name": "Contoso, Ltd. | Office Supply Deals - South Shana",
"location": {
"lat": 40.7128,
"lon": -74.0060
},
"sales": {
"fullSales": 5400
},
"tag": ["#TechDeals", "#FreeShipping"]
}
]
},
{
$project: {
_id: 1,
name: 1,
"location.lat": 1,
"location.lon": 1,
"sales.fullSales": 1,
tags: "$tag" // renames "tag" to "tags"
}
}
]);
此查询将返回以下文档。
[
{
_id: '7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5',
name: 'Lakeshore Retail | Holiday Supply Hub - Marvinfort',
location: { lat: 60.1441, lon: -141.5012 },
sales: { fullSales: 3700 },
tags: [ '#ShopLocal', '#SeasonalSale' ]
},
{
_id: '7e53ca0f-6e24-4177-966c-fe62a11e9af5',
name: 'Contoso, Ltd. | Office Supply Deals - South Shana',
location: { lat: 40.7128, lon: -74.006 },
sales: { fullSales: 5400 },
tags: [ '#TechDeals', '#FreeShipping' ]
}
]
示例 2:与其他管道阶段合并$documents
db.aggregate([
{
$documents: [
{
"_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
"name": "Lakeshore Retail | Holiday Supply Hub - Marvinfort",
"location": {
"lat": 60.1441,
"lon": -141.5012
},
"sales": {
"fullSales": 3700
},
"tag": ["#ShopLocal", "#SeasonalSale"]
},
{
"_id": "7e53ca0f-6e24-4177-966c-fe62a11e9af5",
"name": "Contoso, Ltd. | Office Supply Deals - South Shana",
"location": {
"lat": 40.7128,
"lon": -74.0060
},
"sales": {
"fullSales": 5400
},
"tag": ["#TechDeals", "#FreeShipping"]
}
]
},
{
$match: { "sales.fullSales": { $gt: 4000 } }
},
{
$sort: { "sales.fullSales": -1 }
}
]);
此查询将返回以下文档。
[
{
_id: '7e53ca0f-6e24-4177-966c-fe62a11e9af5',
name: 'Contoso, Ltd. | Office Supply Deals - South Shana',
location: { lat: 40.7128, lon: -74.006 },
sales: { fullSales: 5400 },
tag: [ '#TechDeals', '#FreeShipping' ]
}
]
局限性
- $documents阶段仅在数据库级聚合管道中受支持。 它必须是管道中的第一个阶段才能正常运行。