如何从mongodb集合中合并拆分字段的两个元素?

时间:2019-12-09 19:36:06

标签: mongodb split concat

我在mongodb集合中有github repos URL。 (评论)

url: "https://api.github.com/repos/andymckay/solitude/comments/1573261" 

我想根据斜杠(/)分隔符拆分此字段。 经过这个过程,我下面有数组喜欢。

https:, , api.github.com, repos, andymckay, solitude, .comments, 1573261

比起我想用斜杠运算符连接数组4.和5.的元素; 最后,我想获得一个像这样的字段;

full_name :"andymckay/solitude"

我是mongodb的新人,我通过此查询解决了这个问题

db.getCollection("commentsURL").aggregate([
       {$project: 
          {
             _id:1,
             url2:{$arrayElemAt:[{$split:["$url", "/"]}, 4]},
             url3:{$arrayElemAt:[{$split:["$url", "/"]}, 5]}
          }
       },
       { $addFields: { full_name: { $concat: [ "$url2", "/", "$url3" ] } } },      
       {$out:"comments2"}
     ]);

此查询的结果,它将在下面创建集合;

{ 
    "_id" : ObjectId("5266780cbd35436070000001"), 
    "url2" : "andymckay", 
    "url3" : "solitude", 
    "full_name" : "andymckay/solitude"
}

有什么方法比我的容易吗?

1 个答案:

答案 0 :(得分:0)

db.getCollection("commentsURL").aggregate([
       {$project: 
          {
             _id:1,
             url2:{$arrayElemAt:[{$split:["$url", "/"]}, 4]},
             url3:{$arrayElemAt:[{$split:["$url", "/"]}, 5]}
          }
       },
       { $addFields: { full_name: { $concat: [ "$url2", "/", "$url3" ] } } },      
       {$out:"comments2"}
     ]);

在进行投影查询之后,我可以获得回购的全名;

db.getCollection("comments").find({},{"_id":1,"full_name":1}).forEach(function(doc){
db.comments2.insert(doc);});