如何使用mongodb获取重复密钥的计数?
我有以下Json结构-如何使用mongodb获取重复密钥的计数?,mongodb,Mongodb,我有以下Json结构- [{ cName:"A", "datastores" : [ { "status":"unused" }, { "name" : "datastore1", "status":"used" }, { "name" : "onNetApp7m", "status":"used" }, { "name" : "d
[{
cName:"A",
"datastores" : [
{
"status":"unused"
},
{
"name" : "datastore1",
"status":"used"
},
{
"name" : "onNetApp7m",
"status":"used"
},
{
"name" : "datastore1",
"status":"used"
}
],
},
{
cName:"B",
"datastores" : [
{
"name" : "dsn",
"status":"used"
},
{
"name" : "dsn",
"status":"used"
},
{
"name" : "datastore2",
"status":"used"
}
],
}
]
我只想从数组/列表“ds”中查找计数大于1的名称。
我想要以下输出-
[{
"cName":"A",
"name" : "datastore1",
"count": 2
},
{
"cName":"B",
"name" : "dsn",
"count": 2
}]
目前,为了获得计数,我在代码逻辑中处理它。
是否可以使用mongo从查询本身获取计数???您需要按以下方式进行聚合:
展开
数组数据存储
通过Group
和cName
名称字段对记录进行分组。 获取每组记录的数据存储
计数
- 我们需要匹配的
组现在是
count>1的组
必填字段项目
ds
已更改为datastores
-是打字错误吗?@BatScream是的。。
db.collection.aggregate([
{$unwind:"$datastores"},
{$group:{"_id":{"cName":"$cName","name":"$datastores.name"},"count":{$sum:1}}},
{$match:{"count":{$gt:1}}},
{$project:{"_id":0,"cName":"$_id.cName","name":"$_id.name","count":1}}
])