0
我有一个小问题丝毫$组, 我需要得到指望所有帖子标签(得到tags.post场数)从收集后MongoDB的聚集
我用moongose ODM
邮政例如模型:
var PostSchema = new Schema({
inc: {
type: Number
},
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
tags:{
post:[{ type: Schema.Types.ObjectId, ref: 'Tag'}],
system:[{ type: Schema.Types.ObjectId, ref: 'Tag' }]
}
});
var Post = Mongoose.model('Post', PostSchema, 'posts');
module.exports = Post;
标记示例模型:
var TagSchema = new Schema({
name: {
index: { unique: true },
type: String,
required: true
}
});
var Tag = Mongoose.model('Tag', TagSchema, 'tags');
module.exports = Tag;
结果应该是这样的:
[
{
"tags_id":"12345667",
"count": 4
},
{
"tags_id":"12345668",
"count": 3
},
{
"tags_id":"12345669",
"count": 2
},
{
"tags_id":"12345660",
"count": 1
}
]
在SQL数据库它看起来像
SELECT tag_id, COUNT(*) AS count
FROM posts
GROUP BY tag_id;
我没有经验丝毫的MongoDB
这是我试过
Post.aggregate([
{
$match: {
"tags.post": {
$ne: []
}
},
{
$lookup:{
from: "tags",
localField: "tags.post",
foreignField: "_id",
as: "tags"
}
},
{
$group: {
_id: '$tags._id',
count: {'$sum':1}
}
}], function (err, result) {
if (err) {
return console.log(err);
}
return console.log(result);
});
结果:
[
{
"_id": [
"59ad4cfe454aaf4f46f5dcea",
"59ad4ff994190a4b8acc6871",
"59ad4ff994190a4b8acc6872",
"59ad65bd454aaf4f46f5dd15"
],
"count": 1
},
{
"_id": [
"59ad65bd454aaf4f46f5dd15"
],
"count": 1
},
{
"_id": [
"59ae20e19d094c31d3751781"
],
"count": 1
},
{
"_id": [
"59ad4cfe454aaf4f46f5dcea"
],
"count": 1
},
{
"_id": [
"59ad4fcb454aaf4f46f5dd02"
],
"count": 1
}
]
感谢
你有没有寻求帮助之前尝试过的东西吗? –
我不明白你的问题......当然我试过!但是$组返回列表和重复标签 –
那么为什么你不告诉我们你试过了什么,那么我们可以纠正它?很可能你的'reduce'功能是不正确的。 –