gpt4 book ai didi

mongodb - 如何从mongo管道中检索每个单个数组元素?

转载 作者:行者123 更新时间:2023-12-04 08:13:01 25 4
gpt4 key购买 nike

让我们假设这是一个示例文档在 mongo-db 中的样子,

[
{
"_id": "1",
"attrib_1": "value_1",
"attrib_2": "value_2",
"months": {
"2": {
"month": "2",
"year": "2008",
"transactions": [
{
"field_1": "val_1",
"field_2": "val_2",

},
{
"field_1": "val_4",
"field_2": "val_5",
"field_3": "val_6"
},

]
},
"3": {
"month": "3",
"year": "2018",
"transactions": [
{
"field_1": "val_7",
"field_3": "val_9"
},
{
"field_1": "val_10",
"field_2": "val_11",

},

]
},

}
}
]
所需的输出是这样的,(我只是展示了第 2 个月和第 3 个月)


ID


字段_1
字段_2
field_3


1
2
2008年
val_1
val_2

1
2
2008年
val_4
val_5
val_6

1
3
2018年
val_7

val_9

1
3
2018年
val_10
val_11



我的尝试:
我在 Py-Mongo 中尝试过这样的事情,
pipeline = [
{
# some filter logic here to filter data basically first
},
{
"$addFields": {
"latest": {
"$map": {
"input": {
"$objectToArray": "$months",
},
"as": "obj",
"in": {
"all_field_1" : {"$ifNull" : ["$$obj.v.transactions.field_1", [""]]},
"all_field_2": {"$ifNull" : ["$$obj.v.transactions.field_2", [""]]},
"all_field_3": {"$ifNull" : ["$$obj.v.transactions.field_3", [""]]},
"all_months" : {"$ifNull" : ["$$obj.v.month", ""]},
"all_years" : {"$ifNull" : ["$$obj.v.year", ""]},
}
}
}
}
},
{
"$project": {
"_id": 1,
"months": "$latest.all_months",
"year": "$latest.all_years",
"field_1": "$latest.all_field_1",
"field_2": "$latest.all_field_2",
"field_3": "$latest.all_field_3",

}
}
]

# and I executed it as
my_db.collection.aggregate(pipeline, allowDiskUse=True)
上面实际上是带来数据,但它是将它们放入列表中。有没有办法在 mongo 本身中轻松地将它们每排一个?
以上以这种方式带来数据,


ID


字段_1
字段_2
field_3


1
[“2”、“3”]
[“2008”、“2018”]
[["val_1", "val_4"], ["val_7", "val_10"]]
[["val_2", "val_5"], ["", "val_11"]]
[["", "val_6"], ["val_9", ""]]


非常感谢您对此的宝贵意见以及更好的方法!
谢谢你的时间。
我的 Mongo 版本是 3.4.6,我使用 PyMongo 作为我的驱动程序。您可以在 mongo-db-playground 处查看正在运行的查询

最佳答案

在聚合查询中执行所有过程可能是个坏主意,您可以在客户端执行此操作,
我创建了一个冗长的查询,可能会导致大量数据的性能问题,

  • $objectToArray转换 months对象到数组
  • $unwind解构月份数组
  • $unwind解构 transactions数组并提供索引字段 index
  • $group来自 _id, year, month and index ,并从字段
  • 中的事务中获取第一个对象
  • $project如果您愿意,您可以设计您的回复,否则这是可选的,我已在操场链接中添加
  • my_db.collection.aggregate([
    { # some filter logic here to filter data basically first },
    { $project: { months: { $objectToArray: "$months" } } },
    { $unwind: "$months" },
    {
    $unwind: {
    path: "$months.v.transactions",
    includeArrayIndex: "index"
    }
    },
    {
    $group: {
    _id: {
    _id: "$_id",
    year: "$months.v.year",
    month: "$months.v.month",
    index: "$index"
    },
    fields: { $first: "$months.v.transactions" }
    }
    }
    ], allowDiskUse=True);
    Playground

    关于mongodb - 如何从mongo管道中检索每个单个数组元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65857866/

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