查找和分组

Find and groupby

如果我的 collection

中有以下文件
{ "_id" : 1, "domainName" : "test1.com", "hosting1" : "hostgator.com",    "hosting2" : "hostgator.com",    sID : 1}
{ "_id" : 2, "domainName" : "test2.com", "hosting1" : "cloud.google.com", "hosting2" : "aws.amazon.com",   sID : 2}
{ "_id" : 3, "domainName" : "test3.com", "hosting1" : "aws.amazon.com",   "hosting2" : "cloud.google.com", sID : 2}

假设我想在 hosting1 或 hosting2

中找到 "cloud.google.com"

我会写一个类似

的查询
db.chats.find({$or : [{ hosting1 : 'cloud.google.com'}, { hosting2 : 'cloud.google.com'}]}).pretty(); 

这会为我获取如下两条记录

{ "_id" : 2, "domainName" : "test2.com", "hosting1" : "cloud.google.com", "hosting2" : "aws.amazon.com",   sID : 2}
{ "_id" : 3, "domainName" : "test3.com", "hosting1" : "aws.amazon.com",   "hosting2" : "cloud.google.com", sID : 2}

假设我想查找并分组 "sID" 字段

假设我想在 hosting1 或 hosting2 中找到 "cloud.google.com",然后按 "sID" 进行 GROUPBY:2 表示

我的结果会是

{ "_id" : 2, "domainName" : "test2.com", "hosting1" : "cloud.google.com", "hosting2" : "aws.amazon.com",   sID : 2}

如何为我的上述要求编写查询

我的 sql 查询将是

SELECT *
FROM chats
WHERE (hosting1 = 'cloud.google.com' OR hosting2 = 'cloud.google.com')
GROUPBY sID;

我已经完成了 mongoDB $group 但我无法让它工作

能否请您告诉我如何实现 this.Your 帮助很大 appreciated.Thanks。

您可以使用 Mongo Aggregation using $first and $$ROOT 如下:

db.collection.aggregate({
    $match: {
    $or: [{
        "hosting1": "aws.amazon.com"
    }, {
        "hosting2": "aws.amazon.com"
    }]
    }
}, {
    $group: {
    "_id": "$sID",
    "domain": {
        $first: "$$ROOT"
    }
    }
})

$$ROOT - 它总是引用根文档。这意味着当前正在聚合管道阶段处理的顶级文档。

$first - 它 returns 将表达式应用于按键共享同一组的一组文档中的第一个文档所产生的值。仅当文档按定义的顺序排列时才有意义。

您也可以使用简单的查找查询,例如 -

db.collection.find({
    $or: [{
    hosting1: 'cloud.google.com'
    }, {
    hosting2: 'cloud.google.com'
    }]
}).limit(1)

在您的情况下,您不需要对文档进行分组。请改用 $limit

db.collection.aggregate(
    [
      { $match: 
        { 
          $or : [
                  { hosting1 : 'cloud.google.com' }, 
                  { hosting2 : 'cloud.google.com'}
          ]
        }
      },
      { $limit: 1 }
    ]
)

此外,您确实不需要聚合,您可以使用find方法。

db.collection.find({ 
    $or :[
           { hosting1 : 'cloud.google.com'},
           { hosting2 : 'cloud.google.com'}]
     }
).limit(1)