gpt4 book ai didi

mongodb - 获取数组 mongodb 中的特定字段并作为数组返回

转载 作者:行者123 更新时间:2023-12-02 00:57:34 28 4
gpt4 key购买 nike

我有以下文件:

{
array: [
{
type: 'error',
data: 1
},
{
type: 'error',
data: 2
}
]
}

我是否可以只获取每个数组元素中的数据字段并将其作为数组返回?像下面这样:

[1, 2] // <--- array containing only the data fields

mongodb projection documentation似乎没有涵盖这个?

最佳答案

您可以使用聚合和 $map运营商。

db.collection.aggregate([
{
"$project": { "_id": 0, "data": {
"$map": { "input": "$array", "as": "ar", "in": "$$ar.data" } } }
}
])

产生:

{ "data" : [ 1, 2 ] }

关于mongodb - 获取数组 mongodb 中的特定字段并作为数组返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32873055/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com