这是我的Mongo模型:
Schema = new mongoose.Schema({
userId: {type: mongoose.Schema.Types.ObjectId, required: true, index: true, ref: 'user'},
date: {type: Number, index: true},
coords: {type: [Number], index: '2dsphere', required: true} //not distinct
}
我尝试按以下格式按日期检索不同的坐标:
[[long, lat],[long, lat],[long, lat], ..., [long, lat]]
我写了类似的东西:
module.exports = function(req, res, next) {
var days = req.params.days || 365;
db.model('activity').aggregate([
{$match: {date: {$gte: getDatesFromNumDays(days)[0], $lte: getDatesFromNumDays(days)[1]}}},
{$group: {
_id: '$coords'
}},
], function (err, result) { ... }
不幸的是,让我回来了
[{"_id":[69.60151471655979,42.32299082108329]},{"_id":[-121.9339648456008,37.37375532540034]},{"_id":[-121.907453583667,37.36068282279872]...]
我在这里缺少什么?如何在输出中包含数组?
答案 0 :(得分:1)
与返回MongoDB文档的所有形式的查询一样,聚合框架必须坚持基本的“键/值”形式的结果。
唯一会返回奇异字段结果数组的命令是.distinct()
db.model('activity').distinct(
'coords',
{ "date": {
"$gte": getDatesFromNumDays(days)[0],
"$lte": getDatesFromNumDays(days)[1]
}},
function(err,result) {
// result is a array of the field values only
}
);
-
简单明显的例子:
db.col.insert({ "a": [[1,2],[3,4]] })
db.col.insert({ "a": [[1,2],[5,6]] })
.distinct()
的输出:
db.col.distinct("a")
[ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ]