【发布时间】:2017-02-22 15:56:24
【问题描述】:
我正在使用 node.js 来处理 mongodb。我的查询给了我想要的结果,但我似乎根本无法对其进行排序,无论我尝试按什么排序。
这是一个查询示例
var query = function (db, callback) {
var cursor = db.collection('collection').aggregate({
$match: {
"startdatetime": {
$gte: new Date([fromDate]),
$lte: new Date([toDate])
}
}
},
{$match: {"depth": {$gte: depthFrom, $lte: depthTo}}},
{$unwind: "$dives"}, {$match: {"depth": {$gte: depthFrom, $lte: depthTo}}},
{
$group: {
_id: {year: {$year: "$startdatetime"},depth: "depth"},
average: {$avg: "$"+[parameter]}
}
}, {$sort: {year: 1,depth:1}});
cursor.each(function (err, doc) {
assert.equal(err, null);
if (doc != null) {
console.log(doc);
} else {
callback();
}
})
};
从这里我得到这个结果:
{ _id: { year: 2015, depth: 17.5 }, average: 7.809660041265659 }
{ _id: { year: 2015, depth: 16.5 }, average: 7.849712114661603 }
{ _id: { year: 2016, depth: 17.5 }, average: 7.402677186121112 }
{ _id: { year: 2016, depth: 16.5 }, average: 7.565136208888859 }
我希望得到这样的结果(按年份,然后按深度):
{ _id: { year: 2015, depth: 16.5 }, average: 7.849712114661603 }
{ _id: { year: 2015, depth: 17.5 }, average: 7.809660041265659 }
{ _id: { year: 2016, depth: 16.5 }, average: 7.565136208888859 }
{ _id: { year: 2016, depth: 17.5 }, average: 7.402677186121112 }
我尝试按_id:1、年份和深度排序,但无论我单独尝试还是组合尝试,结果都没有任何反应。
我做错了吗?
提前致谢。
【问题讨论】:
-
发布您收藏的示例文档
标签: javascript node.js mongodb sorting mongodb-aggregation