在mongodb中组合查询输出
可能重复请告诉我是否有类似的答案 我是mongoDB的新手,我不知道这次行动的条款 我有一些类似这样的数据:在mongodb中组合查询输出,mongodb,Mongodb,可能重复请告诉我是否有类似的答案 我是mongoDB的新手,我不知道这次行动的条款 我有一些类似这样的数据: [{ "Name" : "Python", "Month": new Date("2020-01-01"), "K-data":[{"date": new Date("2020-01-01"), "volume&qu
[{
"Name" : "Python",
"Month": new Date("2020-01-01"),
"K-data":[{"date": new Date("2020-01-01"), "volume":1},
{"date": new Date("2020-01-02"), "volume":2},
{"date": new Date("2020-01-03"), "volume":3},
{"date": new Date("2020-01-04"), "volume":4},
{"date": new Date("2020-01-05"), "volume":5},
],
},
{
"Name" : "Python",
"Month": new Date("2020-02-01"),
"K-data":[{"date": new Date("2020-02-01"), "volume":6},
{"date": new Date("2020-02-02"), "volume":7},
{"date": new Date("2020-02-03"), "volume":8},
{"date": new Date("2020-02-04"), "volume":9},
{"date": new Date("2020-02-05"), "volume":10},
],
},
{
"Name" : "Python",
"date": new Date("2020-03-01"),
"K-data":[ {"date": new Date("2020-03-01"), "volume":11},
{"date": new Date("2020-03-02"), "volume":12},
{"date": new Date("2020-03-03"), "volume":13},
{"date": new Date("2020-03-04"), "volume":14},
{"date": new Date("2020-03-05"), "volume":15},
],
}]
我想要得到的是某个日期范围内的K数据(跨不同文档)。
例如,如果我想获取2020-01-03和2020-02-03之间的K数据,下面是实现这一点的代码
db.stock.aggregate([
{$match: {"K-data.date" : { $lt: new Date("2020-02-03"), $gt: new Date("2020-01-02"),}}},
{$project:
{"K-data": {$filter: {
input: '$K-data',
as: 'kdata',
cond: { $and: [
{$gt: ['$$kdata.date', new Date("2020-01-02")]},
{$lt: ['$$kdata.date', new Date("2020-02-03")]}
]}
}},
_id: 0
}}
])
这就是结果:
{
"K-data" : [
{
"date" : ISODate("2020-01-03T00:00:00Z"),
"volume" : 3
},
{
"date" : ISODate("2020-01-04T00:00:00Z"),
"volume" : 4
},
{
"date" : ISODate("2020-01-05T00:00:00Z"),
"volume" : 5
}
]
}
{
"K-data" : [
{
"date" : ISODate("2020-02-01T00:00:00Z"),
"volume" : 6
},
{
"date" : ISODate("2020-02-02T00:00:00Z"),
"volume" : 7
}
]
}
问题是:如何将K数据合并成这样一个数组
{
"K-data" : [
{
"date" : ISODate("2020-01-03T00:00:00Z"),
"volume" : 3
},
{
"date" : ISODate("2020-01-04T00:00:00Z"),
"volume" : 4
},
{
"date" : ISODate("2020-01-05T00:00:00Z"),
"volume" : 5
},
{
"date" : ISODate("2020-02-01T00:00:00Z"),
"volume" : 6
},
{
"date" : ISODate("2020-02-02T00:00:00Z"),
"volume" : 7
}
]
}
你可以用几种不同的方法来做这件事,我认为“最简单”的方法是先做,然后再做 编辑: 就性能而言,我会删除
$unwind
,然后执行以下操作:
db.stock.aggregate([
{
"$group": {
"_id": null,
"K-data": {
"$push": "$K-data"
}
}
},
{
"$project": {
"K-data": {
$reduce: {
input: "$K-data",
initialValue: [],
in: {$concatArrays: ["$$value", "$$this"]}
}
}
}
}
]);
只是好奇,你能想出一个性能优化的版本吗?我添加了我认为最有效的。
db.stock.aggregate([
{
"$group": {
"_id": null,
"K-data": {
"$push": "$K-data"
}
}
},
{
"$project": {
"K-data": {
$reduce: {
input: "$K-data",
initialValue: [],
in: {$concatArrays: ["$$value", "$$this"]}
}
}
}
}
]);