ich ein kleines Problem Whit $ Gruppe haben, ich auf alle Beiträge Tags zählen müssen (auf tags.post Feld zählen bekommen) von Post SammlungMongoDB Aggregation
Ich benutze moongose ODM
Beitrag Beispielmodell :
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;
Tag Beispielmodell:
var TagSchema = new Schema({
name: {
index: { unique: true },
type: String,
required: true
}
});
var Tag = Mongoose.model('Tag', TagSchema, 'tags');
module.exports = Tag;
Das Ergebnis sollte wie folgt sein:
[
{
"tags_id":"12345667",
"count": 4
},
{
"tags_id":"12345668",
"count": 3
},
{
"tags_id":"12345669",
"count": 2
},
{
"tags_id":"12345660",
"count": 1
}
]
In SQL-Datenbank wie es aussah ist haben
SELECT tag_id, COUNT(*) AS count
FROM posts
GROUP BY tag_id;
ich keine Erfahrung Whit MongoDB
Das ist mein versucht
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);
});
Ergebnis:
[
{
"_id": [
"59ad4cfe454aaf4f46f5dcea",
"59ad4ff994190a4b8acc6871",
"59ad4ff994190a4b8acc6872",
"59ad65bd454aaf4f46f5dd15"
],
"count": 1
},
{
"_id": [
"59ad65bd454aaf4f46f5dd15"
],
"count": 1
},
{
"_id": [
"59ae20e19d094c31d3751781"
],
"count": 1
},
{
"_id": [
"59ad4cfe454aaf4f46f5dcea"
],
"count": 1
},
{
"_id": [
"59ad4fcb454aaf4f46f5dd02"
],
"count": 1
}
]
Dank
Haben Sie etwas vor um Hilfe zu bitten versucht? –
Ich habe deine Frage nicht verstanden ... natürlich habe ich es versucht !!! aber $ group return list und duplicate tags –
Warum zeigen Sie uns dann nicht, was Sie dann versucht haben, damit wir es korrigieren können? Höchstwahrscheinlich war Ihre "Reduzieren" -Funktion falsch. –