我在json中有一本书清单如下:
{
"_id" : ObjectId("1"),
"author" : [
"Mary",
"Tony"
],
"booktitle" : "Book1",
"Category" : "Children"
}
{
"_id" : ObjectId("2"),
"author" : [
"Joe",
"Tony"
],
"booktitle" : "Book2",
"Category" : "Children"
}
{
"_id" : ObjectId("3"),
"author" : [
"Joe",
],
"booktitle" : "Book3",
"Category" : "comedy"
}
.......我希望能得到在两个不同的类别上出版书籍的作者的数量。
举上面的例子:玛丽在“孩子”里有书,托尼在“孩子”里有书,乔在“孩子”和“喜剧”里有书。因此,我希望得到数字1,因为乔是唯一一个在不同类别出版书籍的人。
我用mongoDB编写了以下代码,但不知道如何填充匹配部分:
db.collection.aggregate([
{ $match:{ }},
{ $project:{ _id:0, author:1 }},
{ $unwind:"$author" },
{ $group:{ _id:null, count:{ $sum: 1} }}
])发布于 2016-04-16 22:39:01
在聚合管道中有几个错误:
_id of您的$group的一部分。您的聚合应该是这样的(未经测试的):
db.collection.aggregate([
{ $project:{ _id:0, author:1, Category:1 } },
{ $unwind:"$author" },
{ $group:{ _id:"$author", categories:{ $addToSet: "$Category"} } },
{ $match: { categories: { $size: 2 } },
{ $group:{ _id:null, count:{ $sum: 1} }}
])https://stackoverflow.com/questions/36670467
复制相似问题