基本上我想根据月份对民意调查进行分组。
我的模特:
push()
示例数据:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var voteSchema = new Schema({
ip: String,
votedOn: { type: Date, default: Date.now }
});
var choiceSchema = new Schema({
text: String,
votes: [voteSchema]
});
var PollSchema = new Schema({
question: { type: String, required: true },
choices: [choiceSchema]
});
module.exports = mongoose.model('Polls', PollSchema);
但是当我尝试使用类似于https://stackoverflow.com/a/38596913/5871771
的猫鼬创建群组时我收到[
{
"_id": "5914056440bfac03711966ad",
"choices": [
{
"text": "c3",
"_id": "5914056440bfac03711966af",
"votes": [
{
"ip": "::1",
"_id": "5914058040bfac03711966b4",
"votedOn": "2017-05-11T06:32:32.685Z"
}
]
},
{
"text": "c1",
"_id": "5914056440bfac03711966ae",
"votes": [
{
"ip": "::1",
"_id": "587dec8eaccc4b036a193a8f",
"votedOn": "2017-01-17T10:06:06.012Z"
}
]
}
]
},
{
"_id": "5914057540bfac03711966b0",
"choices": [
{
"text": "b3",
"_id": "5914057540bfac03711966b3",
"votes": [
{
"ip": "::1",
"_id": "591d6b8caccc4b036a193a8e",
"votedOn": "2017-05-18T09:38:20.363Z"
}
]
},
{
"text": "b2",
"_id": "5914057540bfac03711966b2",
"votes": [
{
"ip": "::1",
"_id": "591d69b7accc4b036a193a8d",
"votedOn": "2017-05-18T09:30:31.708Z"
},
{
"ip": "::1",
"_id": "587dec9aaccc4b036a193a90",
"votedOn": "2017-01-17T10:06:18.137Z"
}
]
},
{
"text": "b1",
"_id": "5914057540bfac03711966b1",
"votes": [
{
"ip": "::1",
"_id": "587decafaccc4b036a193a91",
"votedOn": "2017-01-17T10:06:39.809Z"
}
]
}
]
}
]
错误
我还尝试使用以下代码进行基本分组
MongoError: can't convert from BSON type missing to Date
但我得到同样的错误
答案 0 :(得分:1)
长时间搜索后找到解决方案:
必须首先
$unwind
数组,以便mongodb
可以访问 数组对象
以下代码工作正常
Poll.aggregate(
// Un-wind the array's to access filtering
{ $unwind: "$choices" },
{ $unwind: "$choices.votes" },
{ $unwind: "$choices.votes.votedOn" },
// Group results to obtain the matched count per key
{ $group: {
_id : { month: { $month: "$choices.votes.votedOn" }, year: { $year: "$choices.votes.votedOn" } },
count: { "$sum": 1 }
}}, function(er, d) {
console.log(d)
}
)
这将导致我需要的东西
[
{ _id: { month: 1, year: 2017 }, count: 3 },
{ _id: { month: 5, year: 2017 }, count: 3 }
]
请参阅$unwind的文档: