本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$first
5.0 版的新增内容。
弹性集群不支持。
Amazon DocumentDB 中的$first操作员返回一组分组文档中的第一个文档。它通常在聚合管道中用来检索与特定条件匹配的第一个文档。
参数
示例(MongoDB 外壳)
以下示例演示如何使用$first运算符检索聚合期间每个类别遇到的第一个项目值。
注意:根据管道中文档的当前顺序$first返回第一个文档。为了确保特定的顺序(例如按日期、价格等),应在$sort舞台之前使用$group舞台。
创建示例文档
db.products.insertMany([
{ _id: 1, item: "abc", price: 10, category: "food" },
{ _id: 2, item: "jkl", price: 20, category: "food" },
{ _id: 3, item: "xyz", price: 5, category: "toy" },
{ _id: 4, item: "abc", price: 5, category: "toy" }
]);
查询示例
db.products.aggregate([
{ $group: { _id: "$category", firstItem: { $first: "$item" } } }
]);
输出
[
{ "_id" : "food", "firstItem" : "abc" },
{ "_id" : "toy", "firstItem" : "xyz" }
]
代码示例
要查看使用该$first命令的代码示例,请选择要使用的语言的选项卡:
- Node.js
-
const { MongoClient } = require('mongodb');
async function example() {
const uri = 'mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false';
const client = new MongoClient(uri);
try {
await client.connect();
const db = client.db('test');
const collection = db.collection('products');
const result = await collection.aggregate([
{ $group: { _id: "$category", firstItem: { $first: "$item" } } }
]).toArray();
console.log(result);
} catch (error) {
console.error('Error:', error);
} finally {
await client.close();
}
}
example();
- Python
-
from pymongo import MongoClient
from pprint import pprint
def example():
client = None
try:
client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
collection = db['products']
result = list(collection.aggregate([
{ '$group': { '_id': '$category', 'firstItem': { '$first': '$item' } } }
]))
pprint(result)
except Exception as e:
print(f"An error occurred: {e}")
finally:
if client:
client.close()
example()