我这样定义数据模型:
import mongoose from 'mongoose';
const schema = mongoose.Schema({
title: {type: String, required: true},
content: {type: String, required: true},
language: {type: String, required: true},
label: [{type: String, required: false}],
createTime: {type: Date, default: Date.now},
updateTime: {type: Date, default: Date.now}
});
const Snippet = mongoose.model('Snippet', schema, 'snippet');
export default Snippet;
我想要的是当我使用时:
Snippet.aggregate({...})
如果数据是:
[{
title: 'a',
content: 'b',
language: 'javascript'
},{
title: 'a',
content: 'b',
language: 'javascript',
label: ['new', 'old']
},
{
title: 'a',
content: 'b',
language: 'javascript',
label: ['old']
}]
那么我想要的结果应该是这样的:
{
languageCount : [
{
language : 'javascript',
count : 3
}],
labelCount : [
{
label : 'new',
count : 1
},
{
label : 'old',
count : 2
}]
}
我不知道如何完成我的“...”部分。
任何对此有任何想法或任何其他方法可以解决它的人请告诉我,非常感谢!
最佳答案
如果您的 mongod
版本 <= 3.2,您可以使用以下管道执行此操作。
[
{
"$unwind":"$label"
},
{
"$group":{
"_id":{
"lang":"$language",
"label":"$label"
},
"count_label_per_lang":{
"$sum":1
}
}
},
{
"$group":{
"_id":"$_id.lang",
"labels":{
"$push":{
"label":"$_id.label",
"count":"$count_label_per_lang"
}
},
"count":{
"$sum":"$count_label_per_lang"
}
}
}
]
关于mongodb - 关于 mongoDB 的聚合难题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42131619/