collection is as follows:
{
_id: ObjectId(7df78ad8902c)
title: "MongoDB Overview",
description: "MongoDB is no sql database",
by_user: "runoob.com",
url: "http://www.runoob.com",
tags: ["mongodb", "database", "NoSQL"],
likes: 100
},
{
_id: ObjectId(7df78ad8902d)
title: "NoSQL Overview",
description: "No sql database is very fast",
by_user: "runoob.com",
url: "http://www.runoob.com",
tags: ["java", "php", "go"],
likes: 10
},
{
_id: ObjectId(7df78ad8902e)
title: "Neo4j Overview",
description: "Neo4j is no sql database",
by_user: "Neo4j",
url: "http://www.neo4j.com",
tags: ["neo4j", "database", "NoSQL"],
likes: 750
},
now we use the above collection to calculate the number of articles written by each author. Using aggregate (), the result is as follows:
> db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : 1}}}])
{
"result" : [
{
"_id" : "runoob.com",
"num_tutorial" : 2
},
{
"_id" : "Neo4j",
"num_tutorial" : 1
}
],
"ok" : 1
}
>
the above example is similar to the sql statement:
select by_user, count (*) from mycol group by by_user
)in the above example, we group the data by the field by_user field and calculate the sum of the same values in the by_user field
< hr >here is the method to get the length of the array
{
"history_id": [1, 2, 3],
"author": "andy",
...
}
db.test.insert({username:"Alex", tags: ["C-sharp", "Java", "CPP"] });
db.test.aggregate(
{$match: {username : "Alex"}},
{$unwind: "$tags"},
{$project: {count:{$add:1}}},
{$group: {_id: null, number: {$sum: "$count" }}}
);
{ "result" : [ { "_id" : null, "number" : 3 } ], "ok" : 1 }
< hr >
here comes the question. If I want to calculate the tags length according to the original grouping, how do I do it