数组情况1:
样列数据:
{
"ip":"127.0.0.1",
"accounts":[
{
"name":"root",
"comment":"root"
},
{
"name":"test",
"comment":"daemon"
}
]
},
{
"ip":"127.0.0.2",
"accounts":[
{
"name":"root1",
"comment":"root"
},
{
"name":"test1",
"comment":"daemon"
}
]
}
嗯,相对accounts中的name进行聚合,理想结果是
image.png
正确语句:
db.test.aggregate([{$unwind: "$accounts" },{$group:{_id:"$accounts.name",total:{$sum:1}}}])
结果:
image.png
值得注意的是:这里de字段必须是_id,否则报错。
聚合后进行模糊查询:
db.test.aggregate([{$unwind: "$accounts" },{$group:{_id:"$accounts.name",total:{$sum:1}}},{$match:{"_id":{$regex:'r',$options:"$i"}}}])
结果:
image.png
参考文章:
https://www.soinside.com/question/NnZtjaS4WwFVxza4PUjiQE
数组情况2:
样列数据:
{
"_id" : ObjectId("5dada978ea1bd537a3624b8c"),
"ip" : "127.0.0.1",
"accounts" : [
"root",
"root1"
]
}
{
"_id" : ObjectId("5dada994ea1bd537a3624b94"),
"ip" : "127.0.0.1",
"accounts" : [
"test1",
"test2"
]
}
根据accounts中元素进行分组。
查询语句:
db.test.aggregate([{$unwind: "$accounts" },{$group:{_id:"$accounts",total:{$sum:1}}}])
结果:
image.png
参考文章:
https://www.cnblogs.com/hapjin/p/7944404.html
注意这两种的区别。
网友评论