@
JCZ2MkKb5S8ZX9pq 今天才上班,才看到。
```js
function myRandom(min, max) {
return Math.round(Math.random() * (max - min)) + min;
}
var id = 1;
for(var uid = 1; uid <= 10; uid++) {
for(var date = 20200610; date <= 20200619; date++){
var num = myRandom(1,100);
db.sample.insertOne({_id: NumberInt(id), uid:NumberInt(uid), date: "" + date, num:NumberInt(num)});
id++;
}
}
```
你想要的查询如下:
```mongodb
db.getCollection('sample').aggregate([{
$group: {
_id: "$uid",
myNum: {
$push: {
"k": "$date",
"v": "$num"
}
}
}
}, {
$project: {
_id: 1,
num: {
$arrayToObject: "$myNum"
}
}
}]);
```
输出结果如下:
```json
{
"_id" : 8,
"num" : {
"20200610" : 92,
"20200611" : 98,
"20200612" : 22,
"20200613" : 53,
"20200614" : 81,
"20200615" : 15,
"20200616" : 61,
"20200617" : 59,
"20200618" : 47,
"20200619" : 43
}
}
```