我不确定这是否可行,但我想在Mongo不同的方法中从网址获取不同的域名。以下是一些示例数据:
{
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"
}
因此,根据示例数据,我希望得到一个独特的查询,只返回网址中的不同域:
{
"0" : "http://mydomain.prep.com",
"1" : "https://newdomain.com",
"2" : "http://olddomain.reference.org"
}
有人可以告诉我如何进行此查询吗?我对Mongo查询很新,并且没有在线找到解决方案。谢谢!
答案 0 :(得分:1)
从MongoDB 2.6.3开始,执行此类操作的字符串处理功能无法使用。您可以通过map / reduce计算不同的域名,您必须编写自己的逻辑来从URL确定域名,但我认为更容易的是在客户端计算域名并插入它在文件中:
{
stuff : "someValue",
moreStuff : "someOtherValue",
url : "http://mydomain.prep.com/post/290837872/myContent"
domain : "mydomain.prep.com"
}
然后您可以使用简单的不同查询
db.urls.distinct("domain")
答案 1 :(得分:0)
对于Mongo 3.x,您可以使用$split
和$arrayElemAt
:
db.test.aggregate([
{ $project : {
domain: {$arrayElemAt: [ { $split: ["$url", "/"] }, 2 ] }
}},
{ $group : {
_id: "$domain" , count : { "$sum" : 1 }
}},
{ $sort:{
_id:1
}}
]);
结果将是:
/* 1 */
{
"_id" : "mydomain.prep.com",
"count" : 2.0
}
/* 2 */
{
"_id" : "newdomain.com",
"count" : 2.0
}
/* 3 */
{
"_id" : "olddomain.reference.org",
"count" : 2.0
}