我有一个包含以下数据的集合:
{
"_id" : ObjectId("5b5066b716d3112cfc2a5deb"),
"username" : "admin",
"password" : "123456",
"token" : "0123",
"bots" : [
{
"name" : "mybot",
"installations" : [
{
"date" : ISODate("2018-07-19T10:23:51.774Z")
},
{
"date" : ISODate("2018-07-19T10:23:51.774Z")
}
],
"commands" : [
{
"name" : "read",
"date" : ISODate("2018-07-19T10:23:51.774Z")
},
{
"name" : "answer",
"date" : ISODate("2018-07-19T10:23:51.774Z")
},
{
"name" : "get",
"date" : ISODate("2018-07-19T11:55:28.858Z")
},
{
"name" : "get",
"date" : ISODate("2018-07-19T11:56:47.419Z")
},
{
"name" : "get",
"date" : ISODate("2018-07-19T11:56:48.499Z")
},
{
"name" : "get",
"date" : ISODate("2018-07-19T11:56:49.089Z")
}
]
}
]
},
{
"_id" : ObjectId("5b50bbfe3ed35b6f2bde6923"),
"username" : "user",
"password" : "123456",
"token" : "44444",
"bots" : [
{
"name" : "anotherBotName",
"installations" : [
{
"date" : ISODate("2018-07-19T16:27:42.012Z")
},
{
"date" : ISODate("2018-07-19T16:27:42.012Z")
}
],
"commands" : [
{
"name" : "update",
"date" : ISODate("2018-07-19T16:27:42.012Z")
},
{
"name" : "update",
"date" : ISODate("2018-07-19T16:27:42.012Z")
}
]
}
]
}
我想执行与SQL等效的查询
SELECT commands.name, COUNT(commands.name), GROUP BY commands.name
并得到如下结果:
[
{update: 2},
{get: 4},
{read: 1},
{answer: 1}
]
但是当我在mongo中执行此查询时:
.collection(collectionName).aggregate({{'$group': {_id: "$bots.commands.name",count:{$sum:1}}}
}).toArray(callback)
我得到这样的结果:
[
{
_id: [
[ 'test', 'test1' ]
],
count: 1
},
{
_id: [
[ 'read', 'answer', 'get', 'get', 'get', 'get' ]
],
count: 1
}
]
我googled and read关于MongoDB中的聚合,但仍然没有太多收获。从SQL迁移到NoN-SQL数据库很困难
我的问题是:
为什么我的查询未显示我想要查看的结果?
如何解决?
谢谢!
答案 0 :(得分:2)
由于架构中有两个嵌套数组,因此在应用$group
之前应两次使用$unwind运算符。在$unwind
之后,您将为每个name
获得单独的文档。试试:
db.col.aggregate([
{
$unwind: "$bots"
},
{
$unwind: "$bots.commands"
},
{
$group: {
_id: "$bots.commands.name",
count: { $sum: 1 }
}
},
{
$replaceRoot: {
newRoot: {
$let: {
vars: { obj: [ { k: "$_id", v: "$count" } ] },
in: { $arrayToObject: "$$obj" }
}
}
}
}
])
在最后阶段,您可以将$replaceRoot与$arrayToObject一起使用,以将_id
设置为最终对象中的键。
输出:
{ "update" : 2 }
{ "get" : 4 }
{ "answer" : 1 }
{ "read" : 1 }