问题描述
Mongo数据库阵列结构:
[
{
"time":[
"2018-12-18T20:16:28.800Z","2018-12-18T20:16:28.800Z","2016-11-14T10:16:32.700Z","2017-09-17T11:16:54.500Z","2016-11-14T10:16:32.700Z"
],"foo":[
2,5,9,6,3,7,8
]
},{
"time":[
"2018-12-18T20:16:28.800Z","bar":[
7,8,4,4
]
}
]
{
"_id":{
"time":"2018-12-18T20:16:28.800Z"
},"time":"2018-12-18T20:16:28.800Z","data":{
"foo":2,"bar":7
},"_id":{
"time":""2018-12-18T20:16:28.800Z"
},"time":""2018-12-18T20:16:28.800Z","data":{
"foo":5,"bar":8
},"_id":{
"time":"2016-11-14T10:16:32.700Z"
},"time":"2016-11-14T10:16:32.700Z","data":{
"foo":9,"bar":9
},"data":{
"foo":6,"bar":4
},"_id":{
"time":"2018-12-18T20:16:28.800Z"
},"data":{
"foo":3,}
我有多个名为foo
和bar
的文档。
我想就时间进行分组,并且Output将是一次性邮票,其中不包含bar
和foo
的值或多个值,并且获取有关时间的多个文档。
解决方法
您可以尝试
-
$project
,$map
使用0
迭代范围从time
到$range
数组大小的循环,返回特定字段,-
time
使用$arrayElemAt
获取元素 -
index
从范围中获取索引 -
data
作为对象,$reduce
使用$$ROOT
转换为数组后,迭代$objectToArray
字段的循环,检查字段名称是否来自foo/bar
然后它将从数字数组中获取元素,并使用$arrayToObject
转换后返回
-
-
$unwind
解构datas
数组 -
$group
按时间和索引排列,并将数据作为对象 -
$sort
按索引字段升序
db.collection.aggregate([
{
$project: {
datas: {
$map: {
input: { $range: [0,{ $size: "$time" }] },as: "a",in: {
time: { $arrayElemAt: ["$time","$$a"] },index: "$$a",data: {
$reduce: {
input: { $objectToArray: "$$ROOT" },initialValue: {},in: {
$cond: [
{ $in: ["$$this.k",["foo","bar"]] },{
$arrayToObject: [[
{
k: "$$this.k",v: { $arrayElemAt: ["$$this.v","$$a"] }
}
]]
},{}
]
}
}
}
}
}
}
}
},{ $unwind: "$datas" },{
$group: {
_id: {
index: "$datas.index",time: "$datas.time"
},time: { $first: "$datas.time" },data: { $mergeObjects: "$datas.data" }
}
},{ $sort: { "_id.index": 1 } }
])