[英]MongoDB aggregation
我有一個小問題,$ group,我需要從帖子集合中獲取所有帖子標簽的計數(在tags.post字段中獲取計數)
我用月光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
}
]
謝謝
只需在$group
使用一個字段,如下所示,
"Count": { "$sum": 1}
這將給您計數。
我找到了解決方案:
Tag.aggregate([
{
$lookup: {
from: "posts",
localField: "_id",
foreignField: "tags.post",
as: "posts"
}
},
{
$unwind: "$posts"
},
{
$group: {_id:"$_id", posts: {$push:"$posts"},name : { $first: '$name' }, size: {$sum:1}}
},
{
$project : { name : 1, size:1 }
},
{
$sort:{size:-1}
},
{
$limit : limit
}
], function (err, result) {
if (err) {
return utils.res.error(res, { message: 'Could not fetch all public tags', reason: err, debug: result })
}
return utils.res.ok(res, result);
})
感謝大家,如果有人有解決方案,請在這里寫下,我將不勝感激
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.