本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$map
Amazon DocumentDB 中的$map运算符允许您将指定的表达式应用于数组中的每个元素,并返回包含已转换元素的新数组。此运算符对于操作和转换数组中的数据特别有用,它可以将数组处理推到数据库级别,从而帮助简化应用程序代码并提高查询性能。
参数
示例(MongoDB 外壳)
以下示例演示如何使用 $map 运算符来转换数字数组,将每个值加倍。
创建示例文档
db.collection.insertMany([
{ _id: 1, numbers: [1, 2, 3, 4, 5] },
{ _id: 2, numbers: [10, 20, 30, 40, 50] }
])
查询示例
db.collection.aggregate([
{
$project: {
doubledNumbers: { $map: { input: "$numbers", as: "num", in: { $multiply: ["$$num", 2] } } }
}
}
])
输出
[
{ _id: 1, doubledNumbers: [2, 4, 6, 8, 10] },
{ _id: 2, doubledNumbers: [20, 40, 60, 80, 100] }
]
代码示例
要查看使用该$map命令的代码示例,请选择要使用的语言的选项卡:
- Node.js
-
const { MongoClient } = require('mongodb');
async function example() {
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('collection');
const result = await collection.aggregate([
{
$project: {
doubledNumbers: { $map: { input: "$numbers", as: "num", in: { $multiply: ["$$num", 2] } } }
}
}
]).toArray();
console.log(result);
await client.close();
}
example();
- Python
-
from pymongo import MongoClient
def example():
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.collection
result = list(collection.aggregate([
{
'$project': {
'doubledNumbers': { '$map': { 'input': '$numbers', 'as': 'num', 'in': { '$multiply': ['$$num', 2] } } }
}
}
]))
print(result)
client.close()
example()