arrays - Mongodb - 在嵌套数组中只取一个元素
问题描述
我正在使用 mongodb 来存储我的数据。我的集合包含一个由类型标识的对象列表,以及每个对象的其他对象列表。
我收藏的一个例子是:
[
{
"type": "a",
"properties": [
{
"value": "value_a",
"date": "my_date_a"
},
{
"value": "value_b",
"date": "my_date_b"
},
...
]
},
...
]
基于上述数据结构,我想按给定类型检索所有集合,为每个集合只取嵌套数组中的一个元素(将嵌套列表减少为只有一个元素的列表)。
因此,给定类型“a”,结果示例可能是:
[
{
"type": "a",
"properties": [
{
"value": "value_a",
"date": "my_date_a"
}
]
},
...
]
我开始尝试这个查询{ "type": "a" }
来过滤集合。但是,我怎么能只取一个“属性”元素呢?我不能使用“切片”运算符。
非常感谢。
解决方案
我从您对 slice 的引用中假设您对匹配特定的嵌套元素不感兴趣,而只是在固定索引处获取一个值(例如,0)。
如果您愿意使用聚合管道,可以在投影中使用 arrayElementAt:
db.collection.aggregate([
// matches documents with type 'a'
{ $match: { type: 'a' } },
// creates a new document for each
{ $project: {
// that contains the original value for type
type: 1,
// and the first element from the original properties for properties
properties: { $arrayElemAt: [ "$properties", 0 ] }
} }
])
推荐阅读
- matplotlib - 每次我更改“figsize”时,大小都不会改变
- c - 如何不为空终止缓冲区?
- mysql - 连接两个表然后计算两列之间的时间差
- r - 将经度/纬度坐标转换为兰伯特等角圆锥投影
- android - 如何验证函数在 Runnable::run() 中被调用
- php - 使用高级自定义字段关系字段帖子类型修复 wordpress/elementor 的自定义查询
- reactjs - 解析错误:“导入”和“导出”可能只出现在顶层(反应)
- php - 如何解码可疑的 PHP 文件
- swift - Firebase - 根据日期获取用户
- r - 我可以以编程方式控制绘图缩放功能而无需在 R 闪亮的应用程序中重新绘图吗?