MongoDB - 如何根据部分字符串查找不同的值

Sha*_*ane 0 mongodb

我不确定这是否可能,但我想从 Mongo 不同方法中的 url 获取不同的域名。这是一些示例数据:

     {
      stuff : "someValue",
      moreStuff : "someOtherValue",
      url : "http://mydomain.prep.com/post/290837872/myContent"
     }
     {
      stuff : "someValue",
      moreStuff : "someOtherValue",
      url : "http://mydomain.prep.com/s/44432/somethingElse"
     }
     {
      stuff : "someValue",
      moreStuff : "someOtherValue",
      url : "https://newdomain.com/ref/2"
     }
     {
      stuff : "someValue",
      moreStuff : "someOtherValue",
      url : "http://olddomain.reference.org/ref/5"
     }
     {
      stuff : "someValue",
      moreStuff : "someOtherValue",
      url : "https://newdomain.com/ref/2342"
     }
     {
      stuff : "someValue",
      moreStuff : "someOtherValue",
      url : "http://olddomain.reference.org/ref/1234"
     }
Run Code Online (Sandbox Code Playgroud)

因此,根据示例数据,我希望获得一个不同的查询,该查询仅返回网址中的不同域:

    {
     "0" : "http://mydomain.prep.com",
     "1" : "https://newdomain.com",
     "2" : "http://olddomain.reference.org"
    }
Run Code Online (Sandbox Code Playgroud)

有人可以告诉我如何执行此查询吗?我对 Mongo 查询很陌生,还没有在网上找到解决方案。谢谢!

aga*_*ian 5

对于 Mongo 3.x,您可以使用$split$arrayElemAt

db.test.aggregate([
  { $project : { 
      domain: {$arrayElemAt: [ { $split: ["$url", "/"] }, 2 ] }
  }},
  { $group : { 
      _id: "$domain" , count : { "$sum" : 1 } 
  }},
  { $sort:{
      _id:1
  }}
]);
Run Code Online (Sandbox Code Playgroud)

结果将是:

/* 1 */
{
    "_id" : "mydomain.prep.com",
    "count" : 2.0
}

/* 2 */
{
    "_id" : "newdomain.com",
    "count" : 2.0
}

/* 3 */
{
    "_id" : "olddomain.reference.org",
    "count" : 2.0
}
Run Code Online (Sandbox Code Playgroud)