jyo*_*ska 4 python mongodb nosql
我有一组文件,每个文件中有20个以上的密钥,密钥因文档而异.某些密钥可能不存在于所有文档中.我正在尝试使用聚合框架运行MongoDB组操作.查询看起来像这样 -
db.collection.aggregate([{'$group': {'count': {'$sum': 1}, '_id': {'location': '$location', 'type': '$type', 'language': '$language'}}}])
Run Code Online (Sandbox Code Playgroud)
在理想情况下,它应该返回应该存在3个键的文档,并对它们执行"分组"操作.但结果看起来像这样 -
{
"result" : [
{
"_id" : {
"location" : "abc",
"type" : "456"
},
"count" : 5
},
{
"_id" : {
"type" : "123",
"language" : "english"
},
"count" : 1
},
{
"_id" : {
"location" : "ghi",
"type" : "9876",
"language" : "latin"
},
"count" : 2
},
{
"_id" : {
"language" : "hebrew",
"type" : "9434"
},
"count" : 3
},
{
"_id" : {
"type" : "525",
"location" : "cari"
},
"count" : 1
},
{
"_id" : {
"language" : "spanish",
"location" : "dff"
},
"count" : 12
},
{
"_id" : {
"location" : "adpj",
"type" : "3463",
"language": "english"
},
"count" : 8
},
{
"_id" : {
"language" : "french",
"location" : "nts"
},
"count" : 6
}
],
"ok" : 1
}
Run Code Online (Sandbox Code Playgroud)
问题是,即使MongoDB找不到我在查询中要求的所有3个键并显示部分分组,它也会进行组操作.我只对获得所有键的结果感兴趣.客户端过滤不是一种选择.任何人都可以帮忙吗?
Phi*_*ipp 10
对于MongoDB的$ group-operator,没有值也是值.
如果要排除不存在所有三个键的任何文档,可以向聚合管道添加$ match -step,过滤任何没有所有这些键的文档.
db.collection.aggregate([
{ $match: {
"type" : { "$exists" : true},
"location" : { "$exists" : true},
"language" : { "$exists" : true}
}
},
{ $group: {
"_id": {
"location": "$location",
"type": "$typ",
"language": "$language"
},
"count": {$sum: 1}
}
}
]);
Run Code Online (Sandbox Code Playgroud)
询问:
db.collection.aggregate([{
$match: {
type: {
"$exists": true
},
location: {
"$exists": true
},
language: {
"$exists": true
}
}
}])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7960 次 |
| 最近记录: |